Handlebars/Mustache - Is there a built in way to loop through the properties of an object?
Built-in support since Handlebars 1.0rc1
Support for this functionality has been added to Handlebars.js, so there is no more need for external helpers.
How to use it
For arrays:
{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}
For objects:
{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}
Note that only properties passing the hasOwnProperty
test will be enumerated.
It's actually quite easy to implement as a helper:
Handlebars.registerHelper('eachProperty', function(context, options) {
var ret = "";
for(var prop in context)
{
ret = ret + options.fn({property:prop,value:context[prop]});
}
return ret;
});
Then using it like so:
{{#eachProperty object}}
{{property}}: {{value}}<br/>
{{/eachProperty }}
EDIT: Handlebars now has a built-in way of accomplishing this; see the selected answer above. When working with plain Mustache, the below still applies.
Mustache can iterate over items in an array. So I'd suggest creating a separate data object formatted in a way Mustache can work with:
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };
for (var prop in o){
if (o.hasOwnProperty(prop)){
mustacheFormattedData['people'].push({
'key' : prop,
'value' : o[prop]
});
}
}
Now, your Mustache template would be something like:
{{#people}}
{{key}} : {{value}}
{{/people}}
Check out the "Non-Empty Lists" section here: https://github.com/janl/mustache.js