Nesting Handlebars 'lookup' with an 'i

2019-08-21 07:31发布

问题:

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?

Example scenario below, where we need to check whether the items in 'arrayOne' exist in '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}}

回答1:

The answer is 'No' as the Handlebars syntax won't permit to nest the if block helper with lookup helper.

The solution is to create a custom helper(isItemExist) to check whether the item in 'arrayOne' exist in the '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.