Question

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

Was it helpful?

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top