row striping and first/last classes with mustache.js

前端 未结 2 2136
庸人自扰
庸人自扰 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}}<span class="{{clazz}}">{{.}}</span>{{/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}}<span class="{{clazz}}">{{name}}</span>{{/arr}}';
    Mustache.to_html(template, view);
    
    0 讨论(0)
  • I recommend doing both of these with pure css/css3, no js required! This seems ideal when the stuff you're trying to do is not dealing with content. The future is now!:

    Css row striping:

    use nth-child();

    http://dev.opera.com/articles/view/zebra-striping-tables-with-css3/

    This won't display for ie7 and ie8 ( http://caniuse.com/#search=nth-child ), but they still get the content, so I consider it a win.

    Styling the last element of a static list:

    #nav li + li + li{
    // Crazy styles on the 3rd li here!
    }
    

    (has good support: http://caniuse.com/#search=sibling )

    Styling the last element of a dynamic list

    Use :last-child.

    div#test p:last-child {color: red;}
    div#test p:first-child {text-decoration: underline;}
    

    :last-child isn't supported in ie7 and ie8 ( http://caniuse.com/#search=last-child ), so be careful that you're doing something that would degrade gracefully here. Strangely, :first-child is, so it's possible you can, say, put coloring on all elements by default and then explicitly remove them from the first child, and that will actually work in all browsers.

    0 讨论(0)
提交回复
热议问题