假设我具有以下JSON和handlebars.js模板:
{
rootPath: '/some/path/',
items:[ {
title: 'Hello World',
href: 'hello-world'
}, {
title: 'About',
href: 'about'
}, {
title: 'Latest News',
href: 'latest-news'
}
}
<script id="test-template" type="text/x-handlebars-template">
<ul class="nav">
{{#each items}}
<li><a href="{{../rootPath}}{{href}}">{{title}}</a></li>
{{/each}}
</ul>
</script>
上面的模板有效,直到我要过滤项目-假设有2个列出一个奇数,另一个列出偶数,这是一个简单的奇数模板:
<script id="test-template" type="text/x-handlebars-template">
<ul class="nav">
{{#each items}}
{{#isOdd @index}}
<li><a href="{{../rootPath}}{{href}}">{{title}}</a></li>
{{/isOdd}}
{{/each}}
</ul>
</script>
和注册助手:
// isOdd, helper to identify Odd items
Handlebars.registerHelper('isOdd', function (rawValue, options) {
if (+rawValue % 2) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
[辅助函数将按预期工作,并且仅渲染奇数项,但是对父上下文的引用丢失了,因此{{../rootPath}}
指令~~未能渲染~~呈现空值。
是否可以通过块帮助器传递Parent上下文?
更改此:
<a href="{{../rootPath}}{{href}}">
对此:
<a href="{{../../rootPath}}{{href}}">
为什么?因为if语句在内部上下文中,所以首先您需要上一层,所以这就是为什么要添加../
查看更多详细信息,请参见:https://github.com/wycats/handlebars.js/issues/196