Row (Zebra) Striping With Mustache.js Using Counters

When I started working with Mustache templates, one of the features I felt was lacking was the ability to track what item was currently being processed by the template. Sure, you can always reference the current item via `` but there’s no way to see how many items have been processed; there’s no counter. This makes it difficult to do things like alternate row colors on a table (a.k.a row or “zebra” striping).

Well, I set about figuring out a way to get around this limitation and here’s what I came up with. Basically, we’re setting up a function called getClass and storing it as a property of the JSON data we’re getting back from the server. Each time the function gets called we check the value of callCounter which is a property of the getClass function (remember, functions are object and can therefore have properties). Each time the function is called, we increment the value of callCounter. If the value is odd we return the string ‘odd’; if it is even we return the string ‘even’.

$(document).on('ready', function() {
    $.getJSON('assets/data/channels.json', {}, function(channelData, textStatus, jqXHr) {
        channelData.getClass = function() {
            channelData.getClass.callCounter = channelData.getClass.callCounter || 0;
            channelData.getClass.callCounter++;
            return channelData.getClass.callCounter % 2 == 0 ? 'even' : 'odd';

        }
        $.get('assets/templates/channelList.mustache.html', function(template, textStatus, jqXhr) {
            var channelList = $('#channels tbody');

            channelList.append(Mustache.render($(template).filter('#channelTpl').html(), channelData))
        });
    });
});

Your template might end up looking something like this:

<script id="channelTpl" type="text/html">

<tr class ="">
    <td></td>
    <td><a href =""></a></td>
</tr>

</script>

Hopefully this helps someone out. If you know of a better way to accomplish this, please let me know in the comments below.