我正在尝试在 Handlebars 中创建 if x in JSON
语句。它有效,只是它不返回正确的选项。
这是index.html:
{{#dinsdag}}
{{#each uitval2}}
{{@key}}
{{/each}}
{{#isIn 7 uitval2}}
<p>klopt</p>
{{else}}
<p>mwah</p>
{{/isIn}}
{{/dinsdag}}
这是 data.js:
$(function(){
var templateScript = $("#entry-template").html();
var theTemplate = Handlebars.compile(templateScript);
var context = { "dinsdag": {
"uitval2": {
"7": "1",
"9": "1",
"11": "1"
},}}
var html = theTemplate(context);
$('.test').html(html);
$(document.body).append(html);
})
最后这是 helper.js,问题应该出在哪里。
Handlebars.registerHelper('isIn', function(waarde, inWaarde, options){
$.each($.parseJSON(JSON.stringify(inWaarde)), function(k, v) {
if (parseInt(k) === parseInt(waarde)){
console.log("true");
return options.fn(this);
}
});
console.log("false");
return options.inverse(this);
});
它确实在控制台中返回 True
,但在渲染的 HTML 中返回 else
选项。
最佳答案
您正在 each()
函数内返回,但这并不会使您的助手返回 false。
但是您可以使用 each()
外部的标志来确定输出。就像这样:
Handlebars.registerHelper('isIn', function(waarde, inWaarde, options){
// Start with false assumption
var isTrue = false;
$.each($.parseJSON(JSON.stringify(inWaarde)), function(k, v) {
if (parseInt(k) === parseInt(waarde)){
// Set outer flag
isTrue = true;
// Break loop
return false;
}
});
if (isTrue) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
文档中的更多信息 ( http://api.jquery.com/jquery.each/ ):
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
关于javascript - 自定义 Handlebars.js 帮助程序不返回 options.fn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35412831/