How to get index in Handlebars each helper?
In a Handlebars {{#each}}
loop, simply use the @index variable to retrieve the index:
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:
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:
Implement it in your template:
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:
Objects Index: The {{@key}} Notion
Both arrays and objects can use these methods for index access:
Tabling Indices
Showcasing your indices in a data table can be quite informative:
Custom Helpers for Updated Methods
When updates in Handlebars or Ember necessitate a change in index access, creating custom helpers can fill the gap:
Alternate Index Access Method
Certain contexts may require using {{_view.contentIndex}}
to access indices.
Was this article helpful?