我是 handlebars.js 的新手,我尝试编写一个简单的 if/else 助手。
我用了this codepen作为指南。
我已经发现您不应该在自定义助手前面使用 #
,但我不明白为什么我仍然会收到此错误。
这是我的index.html
:
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js">
</script>
<script type="text/javascript" src="
https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js"></script>
<script src="data.js"></script>
<script src="helper.js"></script>
</head>
<body>
<script id="entry-template" type="text/x-handlebars-template">
<ul class="test">
{{#each people}}
{{ifThird @index}}
<li>
{{firstName}}
</li>
{{else}}
<li>
{{firstName}}{{lastName}}
</li>
{{/each}}
</ul>
</div>
</div>
</script>
</body>
</html>
...这是data.js
:
$(function(){
var templateScript = $("#entry-template").html();
var theTemplate = Handlebars.compile(templateScript);
var context = {
people: [
{firstName: "Yehuda", lastName: "Katz"},
{firstName: "Carl", lastName: "Lerche"},
{firstName: "Alan", lastName: "Johnson"},
{firstName: "Dik", lastName:"Neok"},
{firstName: "Bob", lastName:"van Dam"},
{firstName: "Erik", lastName: "Leria"}
]
};
var html = theTemplate(context);
$('.test').html(html);
$(document.body).append(html);
})
...这是helper.js
(错误应该在这里):
Handlebars.registerHelper('ifThird', function (index, options) {
if(index%3 == 0){
return options.fn(this);
} else {
return options.inverse(this);
}
});
最佳答案
您需要将模板编辑为:
<ul class="test">
{{#each people}}
{{#ifThird @index}}
<li>
{{firstName}}
</li>
{{else}}
<li>
{{firstName}}{{lastName}}
</li>
{{/ifThird}}
{{/each}}
</ul>
您需要使用 {{#ifThird}} 开始该 block 并使用 {{/ifThird}} 关闭该 block 。
关于javascript - Handlebars 自定义助手错误 : "options.fn is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35370881/