Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"},     {"name":"Luke"},     {"name":"Naomi"}   ] } 

using this:

<ul id="luke_should_be_here"> {{people[1].name}} </ul> 

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

like image 931
lukemh Avatar asked Nov 07 '11 23:11

lukemh


People also ask

How do you access the elements of an array using an index?

Access Array Elements Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

How do you access a specific item in an array?

Accessing Items in an Array An item in a JavaScript array is accessed by referring to the index number of the item in square brackets.


2 Answers

Try this:

<ul id="luke_should_be_here"> {{people.1.name}} </ul> 
like image 59
dhorrigan Avatar answered Sep 21 '22 09:09

dhorrigan


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:

{{people.[1].name}} {{people.1.name}} 

However, the square brackets are required in:

{{#with people.[1]}}   {{name}} {{/with}} 

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?

(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 "")) 
like image 27
Arjan Avatar answered Sep 24 '22 09:09

Arjan