Thymeleaf 條件判斷、迭代遍歷

條件判斷
th:if
進行判斷處理
舉個例子:

<p th:if="${user.getAge()} == '男'">
    性別:男
</p>

這裏使用的是 ModelAndView 傳遞的 user 對象

th:switch 配合 th:case
用來分流處理
舉個例子:

<div th:switch="${user.getAge()}">
    <p th:case="25">
        年齡:25
    </p>
</div>

迭代遍歷
th:each =“i : array”
遍歷對象,和 Java 中的 foreach
舉個例子:前端的在下面

List<User> list = new ArrayList<>();
list.addAll(Arrays.asList(new User("aa", 23, "男"), 
    new User("bb", 22, "男"), new User("cc", 21, "男")));
modelAndView.addObject("users", list);

Thymeleaf 還爲數組的對象提供了一個狀態變量
th:each =“i, var : array”
逗號後面的就是狀態變量,可以獲取 index、count、size、even、odd、first、last
index 索引值
count 計數器
size 數組大小
even 是否是奇數位置
odd 是否是偶數位置
first 是否是第一個
last 是否是最後一個

舉個例子:

<table border="1px">
    <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
        <th>index</th>
        <th>count</th>
        <th>size</th>
        <th>even</th>
        <th>odd</th>
        <th>first</th>
        <th>last</th>
    </tr>
    <tr th:each="u, var : ${users}">
        <td th:text="${u.name}"></td>
        <td th:text="${u.age}"></td>
        <td th:text="${u.gender}"></td>

        <td th:text="${var.index}"></td>
        <td th:text="${var.count}"></td>
        <td th:text="${var.size}"></td>
        <td th:text="${var.even}"></td>
        <td th:text="${var.odd}"></td>
        <td th:text="${var.first}"></td>
        <td th:text="${var.last}"></td>
    </tr>
</table>

th:each 獲取 map 中的值

Map<String, User> map = new HashMap<>();
map.put("u1",new User("aa", 23, "男"));
map.put("u2",new User("bb", 23, "男"));
map.put("u3",new User("cc", 23, "男"));
modelAndView.addObject("userMap", map);

th:each=“maps : ${userMap}”
th:each=“map : ${maps}” 是每行都有的

<table border="1px">
    <tr>
        <th>Key</th>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
    </tr>
    <tr th:each="maps : ${userMap}">
        <td th:each="map : ${maps}" th:text="${maps.key}"></td>
        <td th:each="map : ${maps}" th:text="${map.value.name}"></td>
        <td th:each="map : ${maps}" th:text="${map.value.age}"></td>
        <td th:each="map : ${maps}" th:text="${map.value.gender}"></td>
    </tr>
</table>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章