一、th:each
作用:用于遍歷controller層發送過來的集合。
例:
Controller代碼:
1
2
3
4
5
6
7
8
|
@Controller public class HelloController { @RequestMapping ( "/success" ) public String success(Map<String,Object> map){ map.put( "users" , Arrays.asList( "張三" , "李四" , "王五" )); return "success" ; } } |
下面我們通過th:each屬性在html頁面將其遍歷顯示出來
1
2
3
4
5
6
7
8
9
10
|
<!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為真的時候,顯示本句話,這是用三相表達式做的':''" >
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/bear7/p/13490020.html