thymeleaf th:each使用

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>

结果:

 

 

posted @ 2022-03-08 15:04  基地您  阅读(2919)  评论(0编辑  收藏  举报