bugman
bugman

Reputation: 315

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

Upvotes: 15

Views: 13277

Answers (3)

nickgraef
nickgraef

Reputation: 2417

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

Upvotes: 18

Michael Radionov
Michael Radionov

Reputation: 13319

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" }
    }
}

Upvotes: 4

Zahid Riaz
Zahid Riaz

Reputation: 2889

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}}

Upvotes: 0

Related Questions