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

0

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.