Nesting Handlebars 'lookup' with an 'if'

妖精的绣舞 提交于 2019-12-11 17:44:56

问题


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.



来源:https://stackoverflow.com/questions/48863603/nesting-handlebars-lookup-with-an-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!