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”。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM