In Mustache, How to get the index of the current Section

christophercotton picture christophercotton · Feb 16, 2011 · Viewed 61.2k times · Source

I am using Mustache and using the data

{ "names": [ {"name":"John"}, {"name":"Mary"} ] }

My mustache template is:

{{#names}}
    {{name}}
{{/names}}

What I want to be able to do is to get an index of the current number in the array. Something like:

{{#names}}
    {{name}} is {{index}}
{{/names}}

and have it print out

John is 1
Mary is 2

Is it possible to get this with Mustache? or with Handlebars or another extension?

Answer

dave picture dave · Apr 18, 2012

This is how I do it in JavaScript:

var idx = 0;

var data = { 
   "names": [ 
       {"name":"John"}, 
       {"name":"Mary"} 
    ],
    "idx": function() {
        return idx++;
    }
};

var html = Mustache.render(template, data);

Your template:

{{#names}}
    {{name}} is {{idx}}
{{/names}}