row striping and first/last classes with mustache.js

javascript, mustache

Solution

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

Problem

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? (Obviously, one could always use jquery or whatever to apply a css class after the template has been processed, or whatever, but I'm wondering about something more at the template level.)

Original source