hok*_*oka 22 javascript templates mustache handlebars.js
假设我有以下JSON和handlebars.js模板:
{
rootPath: '/some/path/',
items:[ {
title: 'Hello World',
href: 'hello-world'
}, {
title: 'About',
href: 'about'
}, {
title: 'Latest News',
href: 'latest-news'
}
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
上面的模板工作,直到我想要过滤项目 - 让我们说有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>
Run Code Online (Sandbox Code Playgroud)
和注册助手:
// isOdd, helper to identify Odd items
Handlebars.registerHelper('isOdd', function (rawValue, options) {
if (+rawValue % 2) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Run Code Online (Sandbox Code Playgroud)
帮助程序按预期工作,只渲染Odd项,但是对父上下文的引用会丢失,因此{{../rootPath}}指令~~无法呈现~~呈现空值.
有没有办法通过块Helper传递Parent上下文?
Fra*_*ein 43
修改
<a href="{{../rootPath}}{{href}}"> to this:
<a href="{{../../rootPath}}{{href}}">
Run Code Online (Sandbox Code Playgroud)
为什么?因为if语句在内部上下文中所以首先你需要上升一个级别,这就是为什么你必须添加../
请参阅:https: //github.com/wycats/handlebars.js/issues/196