You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

HandlebarsJS中{{#each}}循环限定执行8次及@index条件判断失效问题求助

Hey there! I see you're having trouble getting the conditional check in your Handlebars loop to work. The core issue here is that Handlebars doesn't support direct comparison expressions like @index < 9 inside {{#if}} blocks out of the box. Let's walk through two solid solutions to get your loop to run only 8 times:

1. Use a Custom Comparison Helper (Great for Reusable Logic)

First, we'll register a helper function that lets us perform comparisons in templates. This is flexible and can be reused across your project for other conditional checks.

Add this JavaScript code before compiling your template:

Handlebars.registerHelper('compare', function(lvalue, operator, rvalue, options) {
    var operators, result;

    // Handle cases where operator is omitted (default to ===)
    if (options === undefined) {
        options = rvalue;
        rvalue = operator;
        operator = "===";
    }

    // Define supported comparison operators
    operators = {
        '==': (l, r) => l == r,
        '===': (l, r) => l === r,
        '!=': (l, r) => l != r,
        '!==': (l, r) => l !== r,
        '<': (l, r) => l < r,
        '>': (l, r) => l > r,
        '<=': (l, r) => l <= r,
        '>=': (l, r) => l >= r
    };

    if (!operators[operator]) {
        throw new Error(`Handlebars Helper 'compare' doesn't recognize operator: ${operator}`);
    }

    result = operators[operator](lvalue, rvalue);
    // Return the appropriate block based on the comparison result
    return result ? options.fn(this) : options.inverse(this);
});

Then update your Handlebars template to use this helper. Since @index starts at 0, we'll check for @index < 8 to get exactly 8 iterations:

<thead>
  <tr>
    {{#each this.attr_name}}
      {{#compare @index '<' 8}}
        <th>{{ this }}</th>
      {{/compare}}
    {{/each}}
  </tr>
</thead>

2. Pre-Slice Your Array (Simpler for One-Off Use)

If you don't need reusable comparison logic, you can just trim your array before passing it to Handlebars to render. This keeps your template clean and avoids helper setup.

In your JavaScript code, slice the attr_name array to keep only the first 8 elements:

// Assume your data object is named `templateData`
templateData.attr_name = templateData.attr_name.slice(0, 8);

// Compile and render as usual
const template = Handlebars.compile(yourTemplateMarkup);
const renderedHtml = template(templateData);

Now your template can be simplified to a straightforward loop—no conditionals needed:

<thead>
  <tr>
    {{#each this.attr_name}}
      <th>{{ this }}</th>
    {{/each}}
  </tr>
</thead>

Either approach will get you the 8-loop behavior you want. The helper method is better if you need to do similar comparisons elsewhere, while slicing the array upfront is quicker for a single use case.

内容的提问来源于stack exchange,提问作者abu abu

火山引擎 最新活动