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

如何在Thymeleaf中实现动态字段名的遍历渲染?

解决Thymeleaf动态遍历字段名并获取对象属性值的问题

Thymeleaf不支持${row.${field[0]}}这种嵌套表达式语法,你可以通过以下两种方式实现需求:

方法一:使用括号语法动态访问属性

这是最简单的实现方式,直接通过括号语法将字段名字符串作为属性名访问:

<tr th:each="row : ${list}">
    <td th:each="field : ${arrayFieldName}" scope="row">
        <span th:text="${row[field[0]]}"></span>
    </td>
</tr>

这里row[field[0]]会把field[0]对应的字符串作为属性名,动态从row对象中获取对应值,效果和你硬编码的${row.nameOfMyField1}完全一致。

方法二:借助Thymeleaf的#fields工具类

如果需要处理嵌套属性(如user.address.city)或更复杂的属性访问场景,可以使用#fields.property()方法:

<tr th:each="row : ${list}">
    <td th:each="field : ${arrayFieldName}" scope="row">
        <span th:text="${#fields.property(row, field[0])}"></span>
    </td>
</tr>

该方法会自动解析属性名,支持多层嵌套的属性路径,适用性更广。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 04:27:16