问题 具有动态索引的Handlebars数组访问


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

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

此刻并没有给我一个解析错误,但在运行时并没有给我任何回报。 如果我做这样的事情:

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

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


5738
2017-07-18 13:05


起源

你找到了解决方法吗?我坚持同样的问题。 - Mathieu


答案:


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


您可以使用 内置的 lookup 帮手

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

运用 lookup,你的例子可以写成

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

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


10
2017-09-29 16:04



这应该是公认的答案 - Jivan


您可以编写一个简单的帮助程序,只是为了从数组中获取值

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

3
2018-02-05 12:14





您需要为您的问题创建一个帮助程序。以下是使用索引值解决问题的示例解决方案。如果你想使用某些条件,你也可以这样做。

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

0
2017-07-19 03:25