Thymleaf中th:each标签遍历list如何获取index

简单介绍:传递给后台一个String类型的list,需要获取到list的每一个元素,然后进行筛选,得到正确的文本值,看代码就明白了

代码:

//后台java代码
//failList是一个String类型的list,存放的是状态码00 01 02 03 04 05 06中的某几种
map.addAttribute("failMsgList",failMsgList);
return VIEW_PATH + "/failDetail";//跳转到失败详情页面 
//html代码
<tr th:each="plan : ${planList}" th:id="${plan.planId}"
th:attr="data-plan-status=${plan.planStatus}">
<td th:text="${plan.planName}"></td>
<td th:text="${plan.planCode}"></td>
<div th:switch="${failMsgList.get(__${planStat.index}__)}">
<td th:case="00">后台系统故障</td>
<td th:case="02">此方案待审核,不支持下架</td>
<td th:case="01">此方案未上架,不支持下架</td>
<td th:case="04">此方案未上架,不支持下架</td>
<td th:case="03">此方案未上架,不支持下架</td>
<td th:case="06">此方案已经下架</td>
<td th:case="*"></td>
</div>
说明:failList里的状态码的获取,通过tr循环到第几行的索引来取

 干货:

<tr th:each="user,userStat:${users}"> 

 userStat是状态变量,如果没有显示设置状态变量,thymeleaf会默 认给个“变量名+Stat"的状态变量。

对arrayList对象users遍历,使用user作为接受参数接收,使用userStat作为users下标值,通过userStat.index得到当前所处下标值;

状态变量有以下几个属性:

  • index:当前迭代对象的index(从0开始计算)
  • count: 当前迭代对象的index(从1开始计算)
  • size:被迭代对象的大小
  • current:当前迭代变量
  • even/odd:布尔值,当前循环是否是偶数/奇数(从0开始计算)
  • first:布尔值,当前循环是否是第一个
  • last:布尔值,当前循环是否是最后一个
    当然,user和userStat可以自己定义名字,如果没定义状态变量,那么thymleaf会自动给一个“变量名+Stat”。

原文地址:https://www.cnblogs.com/xuchao0506/p/9896430.html