Articles in this section

@index data variable

The @index data variable returns the zero-based position of the current element during a #each iteration over an array or object. Use it to number items, track position, or conditionally act on specific elements within a loop.

Syntax

{{#each field}}{{@index}}{{/each}}

Examples

Return the index of each key in an object

{{#each @root.child}}
 {{@index}}
{{/each}}

Input:

{
 "child": {
 "childTitle": "Child Title",
 "childBody": "Child Body"
 }
}

Output: 0 1

childTitle is at index 0 and childBody is at index 1.

Return the index of each element in an array

{{#each @root.people}}
 {{@index}}
{{/each}}

Input:

{
 "people": [
 "Bertram Gilfoyle",
 "Erlich Bachman",
 "Jin Yang"
 ]
}

Output: 0 1 2

The three array elements are at positions 0, 1, and 2 respectively.

Usage notes

  • @index is only available inside a #each block. It has no meaning outside of iteration.
  • Iteration always starts at 0, regardless of the array or object content.
  • To access @index from a parent #each loop inside a nested #each block, use {{@../index}}.
  • To retrieve the key name of the current element rather than its numeric position, use @key data variable instead.