注:如果不需要取動態值,可直接使用html標籤,當然也可以使用Thymeleaf的標籤;當需要動態取值時,則需要使用Thymeleaf標籤。如:
<form id="login" th:action="'@{/boot/login/}id='+${user.id}"><!--url以開頭斜槓開頭,編譯時會把上下文路徑自動補全在url最前面-->>
...
</form>
<form id="login2" action="/boot/login">
</form>
下面開始介紹Thymeleaf的常見屬性
th:action
- 定義後臺控制器的路徑,類似form標籤的action屬性,比如:
<form id="login" th:action="@{/login}">...</form>
th:each
- 這個屬性非常常用,比如從後臺傳來一個對象集合那麼久可以使用此屬性遍歷輸出,它與JSTL中的c:forEach類似,此屬性既可以循環遍歷數組,也可以循環遍歷集合及Map,比如:
<tr th:each="user,interStat:${userlist}">
<td th:text="${userStat.count}"></td><!--變量名加Stat.count即可輸出當前循環對象的個數,從1開始-->
<td th:text="${user.id}"></td>
<td th:text="${user.nick}"></td>
<td th:text="${user.phone}"></td>
<td th:text="${user.email}"></td>
<td th:text="${user.address}"></td>
</tr>
以上代碼解讀如下:
th:each="user,interStat:${userlist}"中的userlist是後臺傳來的Key,user是userlist中的一個數據,interStat是userlist循環體的信息,其中user及interStat自己可以隨便寫;interStat是循環體信息,通過該變量可以獲取如下信息:index、size、count、even、odd、first、last,其含義如下:
- index:當前迭代對象的index(從0開始計算)
- count:當前迭代對象的個數(從1開始計算)
- size:被迭代對象的大小
- current:當前迭代變量
- even/odd:布爾值,當前循環是否是偶數/奇數(從0開始計算)
- first:布爾值,當前循環是否是第一個
- last:當前循環是否是最後一個
注意:循環體信息interStat也可以不定義,則默認採用迭代變量加上Stat後綴,即userStat。
Map類型的循環:
<div th:each="myMapVal:${myMap}">
<span th:text="${myMapVal.key}"></span>
<span th:text="${myMapVal.value}"></span>
<br/>
</div>
myMapVal.key是獲取map中的key,myMapValue.value是獲取map中的value;
數組類型的循環:
<div th:each="myArayVal : ${myArray}">
<div th:text="${myArrayVal}"></div>
</div>
th:if
條件判斷,比如後臺傳來一個變量,判斷該變量的值,1爲男,2爲女:
<span th:if="${sex}==1">
男:<input type="radio" name="se" th:value="男">
</span>
<span th:if="${sex}==2">
女:<input type="radio" name="se" th:value="女">
</span>
th:unless
th:unless是th:if的一個想反操作,上面的例子可以改寫爲:
<span th:unless="${sex}==1">
女:<input type="radio" name="se" th:value="女">
</span>
<span th:if="${sex}==2">
男:<input type="radio" name="se" th:value="男">
</span>
th:switch/th:case
switch,case判斷語句,比如:
<div th:switch="${sex}">
<p th:case="1">性別:男</p>
<p th:case="2">性別:女</p>
<p th:case="*">性別:未知</p>
</div>
一旦某個case判斷值爲true,剩餘的case則都當做false,"*"表示默認的case,前面的case都不匹配的時候,執行默認的case。
th:src
用於外部資源引入,比如script標籤的src屬性,img標籤src屬性,常與@{}表達式結合使用:
<script th:src="@{/static/js/jquery-2.4.min.js}"></script><!--這裏的資源是寫死的,所以這裏也可以直接使用普通的src,動態的則必須用th:src-->
<img th:src="@{/static/image/logo.png}"/>
th:value
類似html標籤中的value屬性,能對某元素的value屬性進行賦值,比如:
<input type="hidden" id="userId" th:value="${userId}">
th:inline內聯文本、內聯腳本(主要用在js取動態數據)
- th:inline有三個取值類型{text,javascript和none},該屬性使用內聯表達式[[…]]展示變量數據,比如:
<span th:line="text">Hello,[[${user.nick}]]</span>
<!--等同於-->
<span>Hello,<span th:text="{user.nick}"></span></span>
<!--th:inline寫在任何父標籤都可以,比如如下也是可以的-->
<body th:inline="text">
...
<span>[[${user.nick}]]</span>
</body>
<!--內聯腳本-->
<script th:inline="javascript" type="text/javascript">
var user = [[${user.phone}]];
alert(user);
</script>
<script th:inline="javascript" type="text/javascript">
var msg = "Hello,"+[[${user.phone}]];
alert(msg);
</script>