【问题标题】:Nesting Handlebars 'lookup' with an 'if'用 'if' 嵌套 Handlebars 'lookup'
【发布时间】:2018-07-29 12:53:03
【问题描述】:

这是关于是否可以将 Handlebars lookup 助手与 if 块助手嵌套的问答,如果不能,是否有任何替代解决方案?

下面的示例场景,我们需要检查 'arrayOne' 中的项目是否存在于 'arrayTwo' 中。

{{#each arrayOne}}
    {{#if lookup ../arrayTwo @index}}
      {{this}} - This arrayOne item is present in arrayTwo
    {{else}}
      {{this}} - This arrayOne item is NOT present in arrayTwo
    {{/if}}
{{/each}}

【问题讨论】:

    标签: javascript handlebars.js helper


    【解决方案1】:

    答案是“否”,因为 Handlebars 语法不允许将 if 块助手与 lookup 助手嵌套。

    解决方法是创建一个自定义的helper(isItemExist)来检查'arrayOne'中的项是否存在于'arrayTwo'中,

    Handlebars.registerHelper("isItemExist", function(array, value, options) {
      return value < array.length ? options.fn(this) : options.inverse(this);
    });
    

    模板是,

    {{#each arrayOne}}
      {{#isItemExist ../arrayTwo @index}}
        {{this}} - This arrayOne item is present in arrayTwo
      {{else}}
        {{this}} - This arrayOne item is NOT present in arrayTwo
      {{/isItemExist}}
    {{/each}}
    

    希望这会有所帮助。

    【讨论】:

    • 这适用于版本 4.3:{{#if (lookup ./arrayTwo @index)}}
    猜你喜欢
    • 2019-04-29
    • 2018-12-12
    • 2012-09-27
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2018-10-06
    相关资源
    最近更新 更多