Handlebars array access with dynamic index

萝らか妹 提交于 2019-12-06 17:55:29

问题


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


回答1:


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




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/17724298/handlebars-array-access-with-dynamic-index

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!