Thymleaf中th:each标签遍历list如何获取index
简单介绍:传递给后台⼀个String类型的list,需要获取到list的每⼀个元素,然后进⾏筛选,得到正确的⽂本值,看代码就明⽩了
代码:
thyme//后台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="${(__${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”。