使用动态索引处理Handlebars数组访问

15
如何在handlebars模板中使用变量而不是硬编码的值访问数组元素?我需要做类似于以下的操作:
{{#each condition in conditions}}
    {{App.ops.[condition.op].name}}
{{/each}}

目前没有给我解析错误,但在运行时没有返回任何结果。如果我做类似这样的事情:

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

它可以运行,但不符合我的要求。

3个回答


4
您可以编写一个简单的助手函数,用于获取数组中的值。
Handlebars.registerHelper('getmyvalue', function(outer, inner) {
    return outer[inner.label];
});

然后在模板中使用它,就像这样:

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

../this指向当前外部项,this指向当前内部项。

模板接收到的数据示例:

{
    outer: {
        1: { foo: "foo value" },
        2: { bar: "bar value" }
    },
    inner: {
        1: { label: "foo" },
        2: { label: "bar" }
    }
}

0
你需要为你的问题创建一个帮助程序。以下是使用索引值解决你的问题的示例方案。如果你想使用一些条件,也可以这样做。
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 "";
});

然后你可以像这样做

{{#each_with_index condition in conditions}}
    {{App.ops.[condition.index].name}}
{{/each_with_index}}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接