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