将'把手''查找'与'如果' [英] Nesting Handlebars 'lookup' with an 'if'
问题描述
如果 block辅助工具是否可以将Handlebars lookup
helper与嵌套,那么问题解答如果没有,有没有其他解决方案呢?
下面的示例场景,我们需要检查'arrayOne'中的项是否存在于'arrayTwo'中。
{{#each arrayOne}}
{{#if lookup ../arrayTwo @index}}
{{this}} - 这个arrayOne物品存在于arrayTwo
{{else}}
{{this}} - 这个arrayOne物品不存在于arrayTwo
{{/ if} }
{{/ each}}
答案是'否',因为Handlebars语法不允许使用查找
助手嵌套 if
块助手。
解决方案是创建一个自定义帮助器( isItemExist
)来检查'arrayOne'中的项是否存在'arrayTwo',
Handlebars.registerHelper( isItemExist,函数(数组,值,选项){
返回值< array.length? options.fn(this):options.inverse(this);
});
模板就是,
{{#each arrayOne}}
{{#isItemExist ../arrayTwo @index}}
{{this}} - 这个arrayOne项存在于arrayTwo
{{else}}
{{this}} - 这个arrayOne项目不在arrayTwo中
{{/ isItemExist}}
{{/ each}}
希望这有助于您。
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}}
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.
这篇关于将'把手''查找'与'如果'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!