Express Handlebars中如何判断{{@index}}奇偶性并传递给助手?
问题解决方法
问题出在你传递@index给自定义助手的写法上——在Handlebars助手的参数里,不需要给变量套额外的{{}}。
你原来的代码:
{{#each org as |building i|}} {{#if (isEven {{@index}})}} ... {{/if}} {{/each}}
这种嵌套{{}}的写法是错误的,Handlebars会无法正确解析参数。
正确写法有两种:
- 直接使用
@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}}
- 既然你已经通过
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
相关产品推荐
相关产品推荐

