You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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' internal options object (we don't need that for value matching).
  • For the or helper: We grab the first argument as our target, then use some() 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 and helper works similarly but uses every() 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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:29:19