如何使用变量而不是硬编码值访问handlebas模板内的数组元素?我需要做一些类似的事情:
{{#each condition in conditions}}
{{App.ops.[condition.op].name}}
{{/each}}
目前没有给我解析错误,但在运行时不会给我任何返回。如果我这样做:
{{App.ops.[1].name}}
它有效,但它不是我想要的
与我对另一个问题的回答有关
您可以使用内置的lookup
助手:
lookup
帮助程序允许使用Handlebars变量进行动态参数解析。这对于解析数组索引的值非常有用。
使用lookup
,您的示例可以写成
{{#each condition in conditions}}
{{#with (lookup ../App.ops condition.op)}}
{{name}}
{{/with}}
{{/each}}
(请注意,在不了解数据结构的情况下,我对App.ops
的位置进行了假设。)
您可以编写一个简单的助手来从数组中获取值
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" }
}
}
您需要为您的问题创建一个帮助程序。下面是使用索引值解决问题的示例。如果你想使用一些条件,你也可以这样做。
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}}