Skip to content Skip to sidebar Skip to footer

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? Example scenario below,

Solution 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.

Post a Comment for "Nesting Handlebars 'lookup' With An 'if'"