Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 739
christophercotton Avatar asked Feb 16 '11 20:02

christophercotton


1 Answers

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}} 
like image 69
dave Avatar answered Sep 17 '22 16:09

dave