You need to enable JavaScript to run this app. 如何在HTML的style属性内正确编写Handlebars条件判断语句
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML的style属性内正确编写Handlebars条件判断语句

问题修复方案

核心报错原因

  • 原生Handlebars不支持在{{if}}块内直接使用!、&&、||这类逻辑运算符,你写的{{if !#data[1]}}属于非法语法,必然触发解析错误
  • 循环上下文内的#data[1]写法兼容性较差,部分Handlebars扩展版本无法正确识别
  • 行内style属性内嵌复杂模板条件,容易和HTML属性解析规则冲突

优先推荐修复方案(改动最小、兼容性最高,5分钟可改完)

完全避免在行内样式中写模板条件,通过动态添加class控制显隐:

  1. 先在样式文件中添加公共类:
.hidden {
    display: none;
}
  1. 修改模板代码如下:
{{for ZippedChoiceResultsArray}}
    <i class="select-btn material-icons unchecked waves-effect {{if this.[1]}}hidden{{/if}}" style="color:#558b2f;" title='{{>~T("StepListTemplateTmpl","ChoiceSetsDone")}}'>check</i>
    <i class="select-btn material-icons checked waves-effect red-text text-darken-4 {{unless this.[1]}}hidden{{/unless}}" title='{{>~T("StepListTemplateTmpl","ChoiceSetsReworkRequired")}}'>flash_on</i>
{{/for}}

备选方案(必须保留行内style写法时使用)

把否定判断换成Handlebars原生的{{unless}}块,同时调整变量引用写法:

{{for ZippedChoiceResultsArray}}
    <i class="select-btn material-icons unchecked waves-effect" style="color:#558b2f;{{if this.[1]}}display:none;{{/if}}" title='{{>~T("StepListTemplateTmpl","ChoiceSetsDone")}}'>check</i>
    <i class="select-btn material-icons checked waves-effect red-text text-darken-4" style="{{unless this.[1]}}display:none;{{/unless}}" title='{{>~T("StepListTemplateTmpl","ChoiceSetsReworkRequired")}}'>flash_on</i>
{{/for}}

验证要点

改完后优先测试两种状态:this.[1]为真、为假时两个按钮的显隐逻辑是否符合预期,确认正常即可上线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 20:15:03