Dre*_*kes 184 javascript handlebars.js
请考虑以下简化数据:
var viewData = {
itemSize: 20,
items: [
'Zimbabwe', 'dog', 'falafel'
]
};
Run Code Online (Sandbox Code Playgroud)
还有一个Handlebars模板:
{{#each items}}
<div style="font-size:{{itemSize}}px">{{this}}</div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为在each
循环中,父作用域不可访问 - 至少不是我尝试过的任何方式.我希望有一种方法可以做到这一点!
Dre*_*kes 393
有两种有效的方法可以实现这一目标.
../
通过预先添加../
到属性名称,可以引用父作用域.
{{#each items}}
<div style="font-size:{{../itemSize}}px">{{this}}</div>
{{#if this.items.someKey}}
<div style="font-size:{{../../itemSize}}px">{{this}}</div>
{{/if}}
{{/each}}
Run Code Online (Sandbox Code Playgroud)
你可以通过重复上升到多个级别../
.例如,上升两个级别使用../../key
.
有关更多信息,请参阅路径上的Handlebars文档.
@root
通过预先添加@root
到属性路径,您可以从最顶层的范围向下导航(如caballerog的答案中所示).
有关更多信息,请参阅有关@data变量的Handlebars文档.
cab*_*rog 52
新方法使用点表示法,不推荐使用斜杠表示法(http://handlebarsjs.com/expressions.html).
因此,访问父元素的实际方法如下:
@root.grandfather.father.element
@root.father.element
Run Code Online (Sandbox Code Playgroud)
在您的具体示例中,您将使用:
{{#each items}}
<div style="font-size:{{@root.viewData.itemSize}}px">{{this}}</div>
{{/each}}
Run Code Online (Sandbox Code Playgroud)
官方文档(http://handlebarsjs.com/builtin_helpers.html)中的另一种方法是使用别名
每个帮助器还支持块参数,允许块中任何位置的命名引用.
Run Code Online (Sandbox Code Playgroud){{#each array as |value key|}} {{#each child as |childValue childKey|}} {{key}} - {{childKey}}. {{childValue}} {{/each}} {{/each}}
将创建一个子项可以访问的键和值变量,而不需要depthed变量引用.在上面的示例中,{{key}}>与{{@ ../key}}相同,但在许多情况下更具可读性.