L. Berger
L. Berger

Reputation: 368

Variable inside handlebars expression

I've got a specific element I want to retrieve from an array, {{page.myArray}}.

I have the index of the element in a variable, {{my-index}}, but I can't just plug in {{page.myArray.[my-index]}} or {{page.myArray.[{{my-index}}].

How do I go about doing this? I've tried out some things from SO and the Handlebars docs, but I can't for the life of me come up with a solution. Hopefully, a kind and generous soul can give me a helping hand here.

Upvotes: 3

Views: 1742

Answers (2)

Nick Asher
Nick Asher

Reputation: 756

I Know this is very late, but you can do this now in handlebars with the lookup helper. You would use it like this

{{lookup page.myArray my-index}}

Upvotes: 0

Gibin Ealias
Gibin Ealias

Reputation: 2859

The answer is a 'no' as Handlebars syntax don't permit the nesting of statements. However, you can write a custom handlebars helper to achieve the same.

Considering your JSON structure as,

{
  "my-index": 1,
  "page": {
    "myArray": [
      "a",
      "b",
      "c"
    ]
  }
}

Your template can be written as below, which is the helper(indexOf) call itself.

{{#indexOf page.myArray my-index}}{{/indexOf}}

And the helper definition would be,

Handlebars.registerHelper('indexOf', function(array, value) {
  return array[value];
});

This will print b as the output as its in the index position 1 of the array myArray.

Tested using http://tryhandlebarsjs.com.

Hope this helps.

Upvotes: 2

Related Questions