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

Thymeleaf循环生成带编号select标签id的问题求助

解决Thymeleaf动态生成id的问题

哈哈,这个问题我之前也踩过坑!Thymeleaf的表达式语法有自己的规则,你之前的写法没符合它的字符串拼接要求,所以要么报错要么直接显示字面量。下面给你两种靠谱的解决方案:

方案1:用字符串拼接符+

Thymeleaf里要把静态字符串和变量拼接,需要把静态字符串用单引号包裹,再和${}变量用+连接,同时整个表达式作为th:id的值:

<tr th:each="item: ${devices}" >
  <select th:id="'selectAuthorizedDriver' + ${item.id}" >
    <!-- 你的选项内容 -->
  </select>
</tr>

原理:Thymeleaf会解析整个'selectAuthorizedDriver' + ${item.id}表达式,把${item.id}的值替换进去,最终生成类似selectAuthorizedDriver1这样的id。

方案2:用Thymeleaf的字面量替换语法|...|

这种写法更简洁,直接把静态内容和变量放在|符号里,Thymeleaf会自动识别并替换变量:

<tr th:each="item: ${devices}" >
  <select th:id="|selectAuthorizedDriver${item.id}|" >
    <!-- 你的选项内容 -->
  </select>
</tr>

这个语法特别适合简单的字符串拼接,代码看起来更清爽。

为啥你之前的写法不行?

  • 第一种写法<select th:id="selectAuthorizedDriver${item.id}" >:Thymeleaf会把整个内容当成表达式,但selectAuthorizedDriver${item.id}不是合法的表达式,所以报错“Could not parse as expression”。
  • 第二种写法<select id="selectAuthorizedDriver${item.id}" >:你用了原生的id属性,Thymeleaf不会解析这个属性里的变量,所以直接显示字面量。
  • 第三种写法<select th:id="selectAuthorizedDriver${id}(id=${item.id})" >:混合了错误的表达式语法,完全不符合Thymeleaf的规则,自然会报错。

记住核心要点:必须用th:id而不是原生id,并且按照Thymeleaf的表达式规则拼接字符串~

内容的提问来源于stack exchange,提问作者Nunyet Calçada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:54:03