我对车把很陌生.js我尝试编写一个简单的 if/else 助手。
我用这个代码笔作为指导方针。
我已经发现您不应该在自定义帮助程序前面使用该#
,但我无法弄清楚为什么我仍然收到此错误。
这是我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}} 关闭块。