Explain Codes LogoExplain Codes Logo

How to get index in Handlebars each helper?

javascript
handlebars
template-engine
javascript-techniques
Anton ShumikhinbyAnton Shumikhin·Jan 1, 2025
TLDR

In a Handlebars {{#each}} loop, simply use the @index variable to retrieve the index:

{{#each items}} <p>{{@index}} - {{this}}</p> <!-- No items were harmed in the making of this loop --> {{/each}}

These lines generate a neat list, each item in a <p> tag along with its position and value.

Key concepts: indices and keys

  • Index access: Use {{@index}} to access the current array index in Handlebars' {{#each}} helper.
  • Key access: Use {{@key}} to access the current property key when looping through objects.
  • Parent access: For nested structures, reach parent index or key with {{@../index}} or {{@../key}}.
  • Default index option: Handlebars 3.0 introduced a syntax to declare an index as a second parameter in "each".

Advanced Usage: Handlebars Techniques

Embracing Handlebars 3.0

In Handlebars version 3.0 and above, you can directly specify an index as a second parameter within the {{#each}} helper:

{{#each array as |value index|}} {{index}}{{value}} <!-- Look Ma, no hands! --> {{/each}}

Boosting Index With Custom Math Helper

In cases where {{@index}} starts at 0 and you needed it to start from a different number, you can expand Handlebars with a custom incrementedIndex function:

Handlebars.registerHelper('incrementedIndex', function (index) { return index + 1; // elevating index from zero to hero });

Implement it in your template:

{{#each items}} <p>{{incrementedIndex @index}} - {{this}}</p> <!-- Indices on steroids --> {{/each}}

Fencing With Empty Arrays

Ensure that your custom helper functions take into account empty arrays to safeguard smooth user experience.

Nested Loops: Parent Indices

In nested scenarios, gaining access to the parent's index or key is crucial:

{{#each outerArray}} {{#each innerArray}} <div>Parent index: {{@../index}}, current index: {{@index}}</div> <!-- It's loops all the way down --> {{/each}} {{/each}}

Objects Index: The {{@key}} Notion

Both arrays and objects can use these methods for index access:

{{#each object}} Key: {{@key}}, Value: {{this}} <!-- Objects have feelings, too --> {{/each}}

Tabling Indices

Showcasing your indices in a data table can be quite informative:

<table> {{#each items}} <tr><td>{{@index}}</td><td>{{this}}</td></tr> <!-- Table manners matter --> {{/each}} </table>

Custom Helpers for Updated Methods

When updates in Handlebars or Ember necessitate a change in index access, creating custom helpers can fill the gap:

Handlebars.registerHelper('indexOffset', function (index) { return index + customOffset; // customOffset: A wild variable appears! });

Alternate Index Access Method

Certain contexts may require using {{_view.contentIndex}} to access indices.