Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

javascript - Access properties of the parent with a Handlebars 'each' loop

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!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two valid ways to achieve this.

Dereference the parent scope with ../

By prepending ../ to the property name, you can reference the parent scope.

{{#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.

Dereference the root scope with @root

By prepending @root to the property path, you can navigate downwards from the topmost scope (as shown in caballerog's answer).

For more information, see the Handlebars documentation on @data variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...