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

如何在Thymeleaf中获取并展示th:each循环的迭代索引?

错误原因

  1. 未在th:each语法中声明迭代状态变量,无法直接调用index/count属性
  2. 循环内直接引用${years}、${bdcInterest}等变量是输出整个数组对象,而非当前迭代位置对应的元素

修正后的HTML代码

<tr th:each="year, iterStat : ${years}" th:unless="${year == null}">
    <!-- 从0开始的迭代索引 -->
    <th scope="row" th:text="${iterStat.index}"></th>
    <!-- 从1开始的迭代索引,替换上面的行即可生效 -->
    <!-- <th scope="row" th:text="${iterStat.count}"></th> -->
    <th scope="row" th:text="${bdcInterest[iterStat.index]}"></th>
    <td th:text="${bdAmount[iterStat.index]}"></td>
</tr>

语法说明

th:each中逗号后声明的iterStat就是官方文档提到的迭代状态对象,你需要的两个属性用法如下:

  • ${iterStat.index}:返回从0开始的当前迭代索引
  • ${iterStat.count}:返回从1开始的当前迭代计数

你代码中years、bdcInterest、bdAmount三个数组的下标是一一对应的,所以通过迭代状态的index属性即可取出另外两个数组对应位置的元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:54:05