如何根据行内值为Handlebars表格的对应单元格设置自定义状态颜色?
实现方案
你现有代码存在两个核心问题:
- Handlebars 原生
{{#if}}不支持直接写===相等判断表达式 - style 属性内多个样式规则之间缺少分号分隔
下面提供两种可直接落地的实现方式:
方案1:动态绑定样式(无需额外注册辅助函数,推荐)
直接把 status 字段值作为类名后缀,通过 CSS 控制不同状态的颜色,后续新增状态只需扩展 CSS 即可:
模板代码
{{#each files}} <tr> <td style="text-align:left">{{filename}}</td> <td class="status-{{status}}" style="text-align:right">{{status}}</td> </tr> {{/each}}
配套CSS
.status-Completed { color: green; } .status-Pending { color: yellow; }
方案2:模板内条件判断
如果要直接在模板内写判断逻辑,需先注册相等比较的 Handlebars 辅助函数:
注册辅助函数(JS端)
Handlebars.registerHelper('eq', function (a, b) { return a === b; });
修正后的模板代码
{{#each files}} <tr> <td style="text-align:left">{{filename}}</td> <td style="text-align:right; {{#if (eq status 'Completed')}}color:green{{else if (eq status 'Pending')}}color:yellow{{/if}}"> {{status}} </td> </tr> {{/each}}
内容的提问来源于stack exchange,提问作者tchris
相关产品推荐
相关产品推荐

