Handlebars.js多参数逻辑AND/OR助手问询:需首个参数参与匹配判断
Custom Handlebars Helpers for Value Matching (AND/OR)
Got it, let's fix this—your original helpers only check if arguments are truthy, but you need to compare the first value against the rest to see if it matches any (for or) or all (for and) of them. Here's the adjusted implementation that fits your exact use case:
Updated Helper Code
Handlebars.registerHelper({ // Checks if the first argument matches ANY of the subsequent values or: function() { // Strip out Handlebars' internal options object (last argument) const args = Array.prototype.slice.call(arguments, 0, -1); const targetValue = args[0]; // Check if target matches any of the remaining arguments return args.slice(1).some(value => value === targetValue); }, // Optional: Checks if the first argument matches ALL subsequent values and: function() { const args = Array.prototype.slice.call(arguments, 0, -1); const targetValue = args[0]; // Check if target matches every remaining argument return args.slice(1).every(value => value === targetValue); } });
What Changed & Why
- We use
slice(0, -1)to exclude the final argument, which is always Handlebars' internaloptionsobject (we don't need that for value matching). - For the
orhelper: We grab the first argument as our target, then usesome()to check if it strictly matches any of the following values—exactly what you need for your{{#if (or questionType 'STARTTIME' 'ENDTIME') }}use case. - The optional
andhelper works similarly but usesevery()to verify the target matches all subsequent values (handy if you ever need that logic).
How to Use
Just like you intended! Here's your exact example in action:
{{#if (or questionType 'STARTTIME' 'ENDTIME') }} <!-- Content renders when questionType is either 'STARTTIME' or 'ENDTIME' --> {{/if}}
Or with more values:
{{#if (or questionType 'STARTTIME' 'ENDTIME' 'ARGUMENT3' 'ARGUMENT4') }} <!-- Content renders when questionType matches any of these four values --> {{/if}}
If you ever need the and helper (e.g., validate a value matches multiple fixed criteria), it works the same way:
{{#if (and userPermission 'EDIT' 'DELETE') }} <!-- Only renders if userPermission is BOTH 'EDIT' and 'DELETE' --> {{/if}}
内容的提问来源于stack exchange,提问作者gene b.
相关产品推荐
相关产品推荐

