问题描述
请考虑以下简化数据:
var viewData = {
itemSize:20,
items :[
'津巴布韦','狗','沙拉三明治'
]
};
还有一个Handlebars模板:
{{#each items}}
< div style =font-size:{{itemSize}} px> {{this}}< / div>
{{/ each}}
这是行不通的,因为在每个
循环,父范围不可访问 - 至少不是我试过的任何方式。我希望有一种方法可以做到这一点!
事实证明,这可以通过将<$ c
$ b $ pre $ {{#each items}} $ $
b $ b< div style =font-size:{{../ itemSize}} px> {{this}}< / div>
{{#if this.items.someKey}}
< div style =font-size:{{../../ itemSize}} px> {{this}}<< ; / DIV>
{{/ if}}
{{/ each}}
您可以通过重复 ../
来升级多个级别。例如,上升两级使用 ../../ key
。
有关更多信息,请参阅。
Consider the following simplified data:
var viewData = {
itemSize: 20,
items: [
'Zimbabwe', 'dog', 'falafel'
]
};
And a Handlebars template:
{{#each items}}
<div style="font-size:{{itemSize}}px">{{this}}</div>
{{/each}}
This won't work because within the each
loop, the parent scope is not accessible -- at least not in any way that I've tried. I'm hoping that there's a way of doing this though!
It turns out that this is possible by prepending ../
to the property name:
{{#each items}}
<div style="font-size:{{../itemSize}}px">{{this}}</div>
{{#if this.items.someKey}}
<div style="font-size:{{../../itemSize}}px">{{this}}</div>
{{/if}}
{{/each}}
You can go up multiple levels via repeating the ../
. For example, to go up two levels use ../../key
.
For more information, see the Handlebars documentation on paths.
这篇关于用Handlebars的'each'循环访问父项的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!