row striping and first/last classes with mustache.js

前端 未结 2 2139
庸人自扰
庸人自扰 2021-02-13 13:50

Frequently one wants to treat the first and/or last items in a list differently from the others. is there a way to do that using mustache? what about row striping?

(Obv

2条回答
  •  礼貌的吻别
    2021-02-13 14:00

    Mustache is very light, so AFAIK, it does not provide that feature.

    You can use something like that, to get even/odd class:

    var view = {
      arr: ['one', 'two', 'three'],
      clazz: function() {
        return _counter++ % 2 == 0 ? 'even' : 'odd';
      }
    };
    
    var template = '{{#arr}}{{.}}{{/arr}}';
    Mustache.to_html(template, view);
    

    Or preprocess the data first, something like that:

    function preprocessArrayWithFirstLastClass(src) {
      var clazz;
      for (var i = 0; i < src.length; i++) {
        clazz = i % 2 == 0 ? 'even' : 'odd';
        if (i == 0) clazz += ' first';
        if (i == src.length - 1) clazz += ' last';
        src[i].clazz = clazz;
      }
    }
    
    var view = {
      arr: preprocessArrayWithFirstLastClass([{name: 'one'}, {name: 'two'}, {name: 'three'}])
    };
    
    var template = '{{#arr}}{{name}}{{/arr}}';
    Mustache.to_html(template, view);
    

提交回复
热议问题