javascript - 自定义 Handlebars.js 帮助程序不返回 options.fn

标签 javascript jquery html handlebars.js

我正在尝试在 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/

相关文章:

javascript - 使用javascript在背景中随机化图像

javascript - 检查 span 元素是否包含超过 3 行

html - 使用 wkhtmltopdf : span issue 将 Twitter Bootstrap 页面转换为 PDF

jquery - 修复了使用 css transition 后标题跳转的问题

javascript - 使用 jquery 克隆 primefaces 组件

javascript - 使用 Javascript 从 HTML 中提取文本

javascript - 简化两个输入变量的 isNaN 函数 - JavaScript

jquery - 是否可以将列表粘贴到 select2 字段并匹配列表中的每个项目?

javascript - Jquery 选择下一个元素内的嵌套元素

javascript - 为什么 JavaScript toLowerCase 不起作用?