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>
demo:
controller:
@GetMapping("/hello5") public String t5(Model model){ String html = "<p style='color:red'>html文本</p>"; model.addAttribute("html",html); model.addAttribute("t1",true); model.addAttribute("t2",true); return "index5"; }
index5.html:
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>index5</title> </head> <body> <p th:if="${t1}" >顯示</p> <p th:if="${not t1}">不顯示</p> <p th:unless="${t1}">不顯示</p> <p th:text="${t2} ? '顯示':'不顯示'"></p> <p th:text="${html}">非轉義的 html 文本</p> <p th:utext="${html}">轉義的 html 文本</p> </body> </html>