row striping and first/last classes with mustache.js

坚强是说给别人听的谎言 提交于 2019-12-03 10:53:25

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);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!