I am using Mustache and using the data
{ \"names\": [ {\"name\":\"John\"}, {\"name\":\"Mary\"} ] }
My mustache template is:
A better approach for Mustache would be using a function that gets the index using indexOf
:
var data = {
names: [ {"name":"John"}, {"name":"Mary"} ],
index: function() {
return data.names.indexOf(this);
}
};
var html = Mustache.render(template, data);
In your template:
{{#names}}
{{name}} is {{index}}
{{/names}}
The drawback is that this index
function has the array hard coded data.names
to make it a more dynamic, we can use another function like this:
var data = {
names: [ {"name":"John"}, {"name":"Mary"} ],
index: function() {
return function(array, render) {
return data[array].indexOf(this);
}
}
};
var html = Mustache.render(template, data);
Usage in your template:
{{#names}}
{{name}} is {{#index}}names{{/index}}
{{/names}}
Also a small drawback is that you have to pass the array name to the index function in this example names
, {{#index}}names{{/index}}
.