You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:05:21