Thymleaf中th:each標籤遍歷list如何獲取index
阿新 • • 發佈:2018-11-02
簡單介紹:傳遞給後臺一個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”。