15

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

bugman
  • 315
  • 2
  • 5
  • 16

3 Answers3

18

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.)

Community
  • 1
  • 1
nickgraef
  • 2,397
  • 2
  • 22
  • 26
  • This solution works for me but I cannot use `{{#each condition in conditions}}` (I get an error: "Must pass iterator to #each"). Instead I have to write `{{#each conditions as |condition|}}`. – Antoine Martin Mar 05 '19 at 15:17
4

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" }
    }
}
Michael Radionov
  • 12,859
  • 1
  • 55
  • 72
0

You need to create a helper for your problem. Below is the sample solution to your problem using index values. If you want to use some conditions you can also do that.

Handlebars.registerHelper("each_with_index", function(array, options) {
    if(array != undefined && array != null && array.length > 0){
        var html = new StringBuffer();
        for (var i = 0, j = array.length; i < j; i++) {
            var item = array[i];
            item.index = i+1;

            // show the inside of the block
            html.append(options.fn(item));
    }

    // return the finished buffer
    return html.toString();
}
return "";
});

Then you can do something like this

{{#each_with_index condition in conditions}}
    {{App.ops.[condition.index].name}}
{{/each_with_index}}
Zahid Riaz
  • 2,879
  • 3
  • 27
  • 38