Today I learned: How to access an array item in a Handlebars template
Posted on
To access an item of an array outside of a each
block helper, for
instance, may not be as a straightforward guess for JavaScript developers, as
the notation is a little bit odd.
Taken the context data of:
{
supportFolks: [
{
fullname: 'John Doe',
},
{
fullname: 'Clark Kent'
}
],
fullnames: [
'John Doe',
'Clark Kent'
]
}
You can access the supportFolks
array items individually as below:
Monday colleague on support is {{supportFolks.[0].fullname}}
Tuesday colleague on support is {{supportFolks.[1].fullname}}
...
what is equivalent to:
Monday colleague on support is {{supportFolks.0.fullname}}
Tuesday colleague on support is {{supportFolks.1.fullname}}
...
Note: Beware though with the ladder. Indeed, if the entry is a non-object
value, you cannot just call fullnames.0
and expect it to work. You would
have to go with fullnames.[0]
.
For that reason I would not recommend using the non-square-bracket
expression as this may lead to confusions down the line.