Counter for handlebars #each

algorithmicCoder picture algorithmicCoder · Mar 1, 2013 · Viewed 30.2k times · Source

In Handlebars, say i have a collection of names how can i do

{{#each names}}
{{position}}
{{name}}
{{/each}}

where {{position}} is 1 for the first name, 2 for the second name etc. Do I absolutely have to store the position as a key in the collection?

Answer

Smix picture Smix · Dec 16, 2013

You can do this with the built-in Handlebars @index notation:

{{#each array}}
  {{@index}}: {{this}}
{{/each}}

@index will give the (zero-based) index of each item in the given array.

Please note for people using Handlebars with the Razor view engine you must use the notation @@index to avoid compilation errors.

For more built-in helpers see http://handlebarsjs.com/