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

Express Handlebars中如何判断{{@index}}奇偶性并传递给助手?

问题解决方法

问题出在你传递@index给自定义助手的写法上——在Handlebars助手的参数里,不需要给变量套额外的{{}}。

你原来的代码:

{{#each org as |building i|}} {{#if (isEven {{@index}})}} ... {{/if}} {{/each}}

这种嵌套{{}}的写法是错误的,Handlebars会无法正确解析参数。

正确写法有两种:

  1. 直接使用@index作为参数(不用套双大括号):
{{#each org as |building|}}
  {{#if (isEven @index)}}
    <div style="background-color: #f0f0f0;">{{building}}</div>
  {{else}}
    <div style="background-color: #ffffff;">{{building}}</div>
  {{/if}}
{{/each}}
  1. 既然你已经通过as |building i|定义了索引变量i,直接传i更直观:
{{#each org as |building i|}}
  {{#if (isEven i)}}
    <div style="background-color: #f0f0f0;">{{building}}</div>
  {{else}}
    <div style="background-color: #ffffff;">{{building}}</div>
  {{/if}}
{{/each}}

为什么原来的写法不行?

在Express Handlebars中,调用助手时,括号内的参数直接写变量名即可,模板插值语法{{}}是用来输出变量的,不是用来在助手参数里传递变量的。你之前的写法相当于把@index的输出字符串传给了isEven,而不是索引本身,导致助手无法正确处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 08:18:34