我已经在车把中创建了一个自定义中断功能,并试图在html中使用它。将html呈现到浏览器时,它没有显示预期的结果。如果标签放错了位置,请纠正我。
<html>
<head>
<title>Hello World</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
<script id="handlebars-demo" type="text/x-handlebars-template">
{{#break students}}
{{name}} has passed in {{passingYear}}.<br>
{{/break}}
</script>
</head>
<body>
{{name}} has passed in {{passingYear}}.<br>
<script>
Handlebars.registerHelper("break", function(data,options) {
var context = {
"students": [{
"name": "mrinal",
"passingYear": 2013
}, {
"name": "raman",
"passingYear": 2016
},
{
"name": "John",
"passingYear": 2018
}]
}
var len = data.length;
var returnData = "";
// custom break function
for (var i = 0; i < len; i++) {
if(data[i].passingYear<2015){
return returnData = returnData + options.fn(data[i]);
i=len+1;
} else{
return returnData = returnData + options.fn(data[i]);
}}
})
var template = $('handlebars-demo').html();
var templateScript = Handlebars.compile(template);
var html = templateScript(context);
$(document.body).append(html);
</script>
</body>
</html>
expected result:
mrinal has passed in 2013.
请仔细阅读代码并分享是否需要更正。
答案 0 :(得分:0)
很多错误:
工作版本如下:
var context = {
"students": [
{
"name": "mrinal",
"passingYear": 2013
},
{
"name": "raman",
"passingYear": 2016
},
{
"name": "John",
"passingYear": 2018
}
]
}
Handlebars.registerHelper("break", function(data,options) {
var len = data.length;
var returnData = "";
// custom break function
for (var i = 0; i < len; i++) {
if(data[i].passingYear<2015){
return returnData = returnData + options.fn(data[i]);
i=len+1;
} else {
return returnData = returnData + options.fn(data[i]);
}
}
});
var template = $('#handlebars-demo').html();
var templateScript = Handlebars.compile(template);
var html = templateScript(context);
$("#placeholder").append(html);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
<script id="handlebars-demo" type="text/x-handlebars-template">
{{#break students}}
{{name}} has passed in {{passingYear}}.<br>
{{/break}}
{{name}} has passed in {{passingYear}}.<br>
</script>
<div id="placeholder"></div>
expected result:
mrinal has passed in 2013.