嵌套把手 'lookup' 与 'if'

Nesting Handlebars 'lookup' with an 'if'

这是一个关于是否可以将 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}}

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

解决方案是创建一个自定义帮助程序(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}}

希望这对您有所帮助。