How do I access an access array item by index in handlebars?

How do I access an access array item by index in handlebars?

I am trying to specify the index of an item in an array within a handlebars template:
people: [
{“name”:”Yehuda Katz”},

using this:


If the above is not possible, how would I write a helper that could access a spefic item within the array?


Solution 1:

Try this:

<ul id="luke_should_be_here">

Solution 2:

The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:


However, the square brackets are required in:

{{#with people.[1]}}

In the latter, using the index number without the square brackets would get one:

Error: Parse error on line ...:
...     {{#with people.1}}                
Expecting 'ID', got 'INTEGER'

As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?

Related:  Why is JavaScript called JavaScript, since it has nothing to do with Java? [closed]

(Tested with Handlebars in YUI.)

2.xx Update

You can now use the get helper for this:

(get people index)

although if you get an error about index needing to be a string, do:

(get people (concat index ""))

Solution 3:

{{#each array}}

Solution 4:

If undocumented features aren’t your game, the same can be accomplished here:

Handlebars.registerHelper('index_of', function(context,ndx) {
  return context[ndx];

Then in a template

{{#index_of this 1}}{{/index_of}}   

I wrote the above before I got a hold of


I can’t see one getting too far with handlebars without writing your own helpers.

Solution 5:

If you want to use dynamic variables

This won’t work:

{{#each obj[key]}}

You need to do:

{{#each (lookup obj key)}}

see handlebars lookup helper and handlebars subexpressions.

Solution 6:

Please try this, if you want to fetch first/last.

{{#each list}}

    {{#if @first}}
        <div class="active">


{{#each list}}

    {{#if @last}}
        <div class="last-element">