Thymeleaf中如何动态设置Input的list属性以简化重复代码?
简化Thymeleaf重复Input代码的方案
问题背景
现有两段几乎完全一致的Thymeleaf Input代码,仅当满足#arrays.contains(dropDownFields, y)条件时,其中一个Input需要额外添加list="list"属性,希望合并重复代码,实现动态设置元素属性。
现有重复代码:
<input th:if="${fieldIndex == 0 && !#arrays.contains(dropDownFields, y)}" th:disabled="${#arrays.contains(disabledFields, y)}" th:field="*{ZMatrixValues[__${dataIndex}__].tableValues[__${i}__][__${y}__]}" class="table-input" type="text" onfocus="focused(this)"> <input th:if="${fieldIndex == 0 && #arrays.contains(dropDownFields, y)}" list="list" th:disabled="${#arrays.contains(disabledFields, y)}" th:field="*{ZMatrixValues[__${dataIndex}__].tableValues[__${i}__][__${y}__]}" class="table-input" type="text" onfocus="focused(this)">
解决方案
Thymeleaf支持条件化设置属性,可以通过th:list结合三元表达式实现动态添加属性,将两段代码合并为一个:
<input th:if="${fieldIndex == 0}" th:list="${#arrays.contains(dropDownFields, y) ? 'list' : null}" th:disabled="${#arrays.contains(disabledFields, y)}" th:field="*{ZMatrixValues[__${dataIndex}__].tableValues[__${i}__][__${y}__]}" class="table-input" type="text" onfocus="focused(this)">
原理说明
- 当
#arrays.contains(dropDownFields, y)为true时,th:list会渲染为list="list"属性; - 当条件为
false时,三元表达式返回null,Thymeleaf会自动忽略该属性,不会在最终HTML中输出; - 同时将原来两个
th:if的公共条件fieldIndex == 0提取出来,进一步精简代码。
另外也可以用th:attr语法实现,效果一致:
<input th:if="${fieldIndex == 0}" th:attr="${#arrays.contains(dropDownFields, y) ? 'list=list' : ''}" th:disabled="${#arrays.contains(disabledFields, y)}" th:field="*{ZMatrixValues[__${dataIndex}__].tableValues[__${i}__][__${y}__]}" class="table-input" type="text" onfocus="focused(this)">
内容的提问来源于stack exchange,提问作者rocketcrafter
相关产品推荐
相关产品推荐

