Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

Ben picture Ben · Jan 30, 2012 · Viewed 120.7k times · Source

As the title of question says, is there a mustache/handlebars way of looping through an object properties?

So with

var o = {
  bob : 'For sure',
  roger: 'Unknown',
  donkey: 'What an ass'
}

Can I then do something in the template engine that would be equivalent to

for(var prop in o)
{
    // with say, prop a variable in the template and value the property value
}

?

Answer

Jon picture Jon · Jul 8, 2013

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.