thymeleaf——th:each、th:if的使用


一、th:each 

作用:用於遍歷controller層發送過來的集合。

例:

Controller代碼:

@Controller
public class HelloController {
    @RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("users", Arrays.asList("張三","李四","王五"));
        return "success";
    }

}

下面我們通過th:each屬性在html頁面將其遍歷顯示出來

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body>

<h4 th:text="${user}" th:each="user:${users}"></h4>

</body> </html>

講解: 

th:each="user:${users}"

  其中${users}是將取出名為users的List集合,每次遍歷取出List集合中的一個元素賦值給user

 

注意:th:each每次遍歷都會生成一個包含它的標簽,如我們舉的這個例子,users中一共有三個元素,所以會遍歷三次,每次都會生成一個h4標簽

 

二、th:if

Thymeleaf 的條件判斷是 通過 th:if 來做的,只有為真的時候,才會顯示當前元素

 

<p th:if="${testBoolean}" >如果testBoolean 是 true ,本句話就會顯示</p>

 

取反可以用not, 或者用th:unless.

<p th:if="${not testBoolean}" >取反 ,所以如果testBoolean 是 true ,本句話就不會顯示</p>
<p th:unless="${testBoolean}" >unless 等同於上一句,所以如果testBoolean 是 true ,本句話就不會顯示</p>

除此之外,三元表達式也比較常見

 

 

<p th:text="${testBoolean}?'當testBoolean為真的時候,顯示本句話,這是用三相表達式做的':''" ></p>

 


免責聲明!

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



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