[英]Handlebars custom helper error: “options.fn is not a function”
我是handlebars.js的新手,我嘗試編寫一個簡單的if / else幫助器。
我用這個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}}啟動塊並使用{{/ ifThird}}關閉塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.