How to get index in Handlebars each helper?

thunderboltz picture thunderboltz · Aug 9, 2012 · Viewed 176.1k times · Source

I'm using Handlebars for templating in my project. Is there a way to get the index of the current iteration of an "each" helper in Handlebars?

<tbody>
     {{#each item}}
         <tr>
            <td><!--HOW TO GET ARRAY INDEX HERE?--></td>
            <td>{{this.key}}</td>
            <td>{{this.value}}</td>
         </tr>
     {{/each}}
</tbody>

Answer

ro60 picture ro60 · Jan 1, 2013

In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.


snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811

The index of the current array item has been available for some time now via @index:

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

For object iteration, use @key instead:

{{#each object}}
    {{@key}}: {{this}}
{{/each}}