Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars array access with dynamic index

How can I access to an array element inside handlebars template using a variable instead of an hardcoded value? I need to do something like:

{{#each condition in conditions}}
    {{App.ops.[condition.op].name}}
{{/each}}

at the moment doesn't give me a parse error but on runtime doesn't return me nothing. If i do something like this:

{{App.ops.[1].name}}

it works but it's not what i'm looking for

like image 518
bugman Avatar asked Jul 18 '13 13:07

bugman


Video Answer


2 Answers

Related to my answer on another question


You can use the built-in lookup helper:

The lookup helper allows for dynamic parameter resolution using Handlebars variables. This is useful for resolving values for array indexes.

Using lookup, your example could be written as

{{#each condition in conditions}}
    {{#with (lookup ../App.ops condition.op)}}
        {{name}}
    {{/with}}
{{/each}}

(Note that without knowledge of the structure of your data, I'm making an assumption about the location of App.ops.)

like image 143
nickgraef Avatar answered Sep 22 '22 19:09

nickgraef


You can write a simple helper just to get value from array

Handlebars.registerHelper('getmyvalue', function(outer, inner) {
    return outer[inner.label];
});

and then use it in template like

{{#each outer}}
    {{#each ../inner}}
        {{getmyvalue ../this this }}
{{/each}}

../this references to current outer item, and this - to current inner item

Example of data coming to template:

{
    outer: {
        1: { foo: "foo value" },
        2: { bar: "bar value" }
    },
    inner: {
        1: { label: "foo" },
        2: { label: "bar" }
    }
}
like image 43
Michael Radionov Avatar answered Sep 19 '22 19:09

Michael Radionov