th:each 循環遍歷,支持 Iterable、Map、數組等。
遍歷list時 th:each="temp,status :${list} temp和status可以隨便取名
temp為list中的對象,status為遍歷的狀態對象
可以使用的屬性為:
index 當前索引,從0開始
count 統計屬性,從1開始
size 遍歷對象中對象的個數
current 當前對象
even 當前索引是否為偶數
odd 當前索引是否為奇數
first 當前遍歷對象是否是第一個
last 當前對象是否是最后一個
遍歷map時,使用 getKey() 獲取當前對象的key
使用 getValue() 獲取當前對象的value
遍歷list演示:
Java代碼
1 @RequestMapping("/th2") 2 public String th2(Model model) { 3 List<String> list = new ArrayList<>(); 4 list.add("zhangsan"); 5 list.add("lisi"); 6 list.add("wangwu"); 7 model.addAttribute("list", list); 8 return "thymeleaf"; 9 }
html:
1 <!-- 2 th:each 循環遍歷,支持 Iterable、Map、數組等。 3 遍歷list時 th:each="temp,status :${list} temp和status可以隨便取名 4 temp為list中的對象,status為遍歷的狀態對象 5 可以使用的屬性為: 6 index 當前索引,從0開始 7 count 統計屬性,從1開始 8 size 遍歷對象中對象的個數 9 current 當前對象 10 even 當前索引是否為偶數 11 odd 當前索引是否為奇數 12 first 當前遍歷對象是否是第一個 13 last 當前對象是否是最后一個 14 遍歷map時,使用 getKey() 獲取當前對象的key 15 使用 getValue() 獲取當前對象的value 16 --> 17 <table border="1px" cellspacing="0px"> 18 <tr> 19 <td>index</td> 20 <td>count</td> 21 <td>size</td> 22 <td>current</td> 23 <td>even</td> 24 <td>odd</td> 25 <td>first</td> 26 <td>last</td> 27 <td>值</td> 28 </tr> 29 <tr th:each="temp,status : ${list}"> 30 <td th:text="${status.index}"></td> 31 <td th:text="${status.count}"></td> 32 <td th:text="${status.size}"></td> 33 <td th:text="${status.current}"></td> 34 <td th:text="${status.even}"></td> 35 <td th:text="${status.odd}"></td> 36 <td th:text="${status.first}"></td> 37 <td th:text="${status.last}"></td> 38 <td th:text="${temp}"></td> 39 </tr> 40 </table>
結果:
遍歷map演示:
Java代碼:
1 @RequestMapping("/th2") 2 public String th2(Model model) { 3 4 Map<String, String> map = new HashMap<>(); 5 map.put("key1", "value1"); 6 map.put("key2", "value2"); 7 map.put("key3", "value3"); 8 9 model.addAttribute("map", map); 10 11 return "thymeleaf"; 12 }
html:
<div th:each=" temp : ${map}"> <span th:text="${temp}"></span> <span th:text=" 'key:'+ ${temp.getKey()}"></span> <span th:text=" 'value'+${temp.getValue()}"></span> </div>
結果: