如何在HTML的style属性内正确编写Handlebars条件判断语句
问题修复方案
核心报错原因
- 原生Handlebars不支持在
{{if}}块内直接使用!、&&、||这类逻辑运算符,你写的{{if !#data[1]}}属于非法语法,必然触发解析错误 - 循环上下文内的
#data[1]写法兼容性较差,部分Handlebars扩展版本无法正确识别 - 行内style属性内嵌复杂模板条件,容易和HTML属性解析规则冲突
优先推荐修复方案(改动最小、兼容性最高,5分钟可改完)
完全避免在行内样式中写模板条件,通过动态添加class控制显隐:
- 先在样式文件中添加公共类:
.hidden { display: none; }
- 修改模板代码如下:
{{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
相关产品推荐
相关产品推荐

