用Handlebars的'each'循环访问父项的属性 [英] Access properties of the parent with a Handlebars 'each' loop

查看:189
本文介绍了用Handlebars的'each'循环访问父项的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下简化数据:

  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'循环访问父项的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆