简体   繁体   English

嵌套把手“查找”和“ if”

[英]Nesting Handlebars 'lookup' with an 'if'

This is a Q&A on whether it is possible to nest the Handlebars lookup helper with if block helper and if not, are there any alternative solutions to it? 这是一个关于是否可以将Handlebars lookup帮助器与if块帮助器嵌套在一起(如果不能嵌套)的问与答,是否有其他替代解决方案?

Example scenario below, where we need to check whether the items in 'arrayOne' exist in 'arrayTwo'. 下面的示例场景中,我们需要检查“ arrayTwo”中是否存在“ arrayOne”中的项目。

{{#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}}

The answer is 'No' as the Handlebars syntax won't permit to nest the if block helper with lookup helper. 答案为“否”,因为Handlebars语法不允许将if块帮助程序与lookup帮助程序嵌套在一起。

The solution is to create a custom helper( isItemExist ) to check whether the item in 'arrayOne' exist in the 'arrayTwo', 解决方案是创建一个自定义帮助器( isItemExist ),以检查“ arrayOne”中的项目是否存在于“ arrayTwo”中,

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

And the template would be, 模板就是

{{#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}}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM