Access array value with index in Handlebars

Say we want a table listing all the data in the following model:

// model hook in a route

model() {
  return [
    [1, "text a"],
    [2, "text b"],
    [3, "text c"],
  ]
}

How do we access each item by index in the Handlebars template?

Use the dot-bracket notation

Here’s how:

<ul>
{{#each model as |item|}}
  <li>
    {{item.[0]}}: {{item.[1]}}
  </li>
{{/each}}
</ul>

Which will output:

<ul>
  <li>
    1: text a
  </li>
  <li>
    2: text b
  </li>
  <li>
    3: text c
  </li>
</ul>

When the array items are objects, we can drop the brackets and simply write:

<ul>
{{#each model as |item|}}
  <li>
    {{item.0.text}}: {{item.1.text}}
  </li>
{{/each}}
</ul>

Need to know the index of the current iteration?

To get the index within an #each helper loop, we use:

{{#each model as |item index|}}
  Index is: {{index}}
{{/each}}

Enjoyed this article? Don't miss my next one!

Leave me your e-mail for content that will help you master Ember:

Do you want to master Ember fast?

Leave me your e-mail for helpful updates delivered straight to your inbox.

(A few e-mails per month. No BS. Unsubscribe anytime!)