How do I access an array item by index in handlebars?
To access array items by index in Handlebars, use the lookup
helper:
Replace array
with your array variable and index
with the numeric index. For instance:
This outputs 'banana' because, like discount sales during black friday, index counting starts at 0.
Direct indexing using dot notation
When you're on a first-name basis with your array item, crack into it directly without helpers using dot notation:
Here, 1
is the index inside the people
array, and .name
is your friendly neighborhood key.
Custom helpers for the pros
If your array indexing is less about flirting and more about business, you may want to take your relationship further with a custom helper:
This "flirts" with the third person in your people
array:
Dynamic array access - Keep things spicy
If you want to keep your index guessing (and avoid any "you're too predictable" drama), then lookup
helper comes to your rescue:
Here, someDynamicIndex
is your honest-to-God chosen index.
Loop it over with @index
and #each
Unwrap your array items one by one with @index
and the #each
loop like it's Christmas morning:
Square brackets for explicit indexing
You know the old saying, "With great power comes great #with
". Here's an example:
This puts you in the second person’s context (don't read into this too much, it's purely platonic).
Be polite, handle your index
Unlike your mean colleagues, Handlebars needs careful handling. If your index is anticipated as a number but enters like a bull in a china shop as a string, that's a recipe for disaster. Here's a-made-for-tv-drama helper function to handle this:
And the polite usage is:
Subexpressions, you showoff!
Subexpressions are the party tricks of the Handlebars world - complex, impressive, and a surefire crowd-pleaser.
Every party needs a street, right? And you just fetched it.
Visualization
Visualise your handlebars array acccess like a kid in a candy store. The array is the candy rack, your item lives in a candy box
(🍬), your index
is like the little numbered tag below:
With your index
you directly point to your favorite candy:
Best practices - Keeping it on fleek
Handlebars is the cool kid on the block, but like all cool kids, it has its quirks. Here are a few tips for accessorizing your Array in style:
-
Don't overcomplicate expressions. If your access logic looks like a space mission, consider moving it into a custom helper.
-
Be careful with named indexes. Using
{{people.John}}
might seem like a good idea, but remember - not everyone is calledJohn
. -
Play nice with different Handlebars versions. Those shapeshifters can throw a curveball at your syntax.
-
Learn from your peers. If an answer on Stackoverflow has handles similar to yours, give it a read for community wisdom.
Was this article helpful?