15

如何使用变量而不是硬编码值访问车把模板内的数组元素?我需要做类似的事情:

{{#each condition in conditions}}
    {{App.ops.[condition.op].name}}
{{/each}}

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

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

它有效,但这不是我想要的

4

3 回答 3

18

我对另一个问题的回答有关


您可以使用内置lookup助手

lookup帮助程序允许使用 Handlebars 变量进行动态参数解析。这对于解析数组索引的值很有用。

使用lookup,您的示例可以写为

{{#each condition in conditions}}
    {{#with (lookup ../App.ops condition.op)}}
        {{name}}
    {{/with}}
{{/each}}

(请注意,在不了解您的数据结构的情况下,我正在对 的位置做出假设App.ops。)

于 2015-09-29T16:04:34.757 回答
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" }
    }
}
于 2014-02-05T12:14:21.893 回答
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}}
于 2013-07-19T03:25:13.037 回答