一、th:if基礎使用
th:if是Thymeleaf中的條件判斷語句,用於根據某個條件來控制HTML的渲染。
使用th:if的基本格式如下:
<div th:if="${isTrue}">
This will be rendered if isTrue is true.
</div>
其中,${isTrue}是在上下文中定義的變量,表示該變量的值如果為true則渲染div標籤內的內容,否則不渲染。
在實際應用中,th:if通常與th:text和th:utext一起使用,來動態地渲染HTML內容:
<span th:if="${user.isAdmin}" th:text="${'Welcome, ' + user.name}">
<span th:unless="${user.isAdmin}" th:text="Welcome, guest">
</span>
以上代碼根據用戶是否為管理員來動態地渲染不同的歡迎信息。如果用戶是管理員,則渲染”Welcome, 用戶名”;否則,渲染”Welcome, guest”。
二、th:if和th:else的使用
在th:if語句基礎上,我們可以使用th:else來表示,如果條件不滿足,則渲染其他內容:
<span th:if="${user.isAdmin}" th:text="${'Welcome, ' + user.name}">
<span th:else th:text="Welcome, guest">
</span>
以上代碼表示,如果用戶是管理員,則渲染”Welcome, 用戶名”;否則,渲染”Welcome, guest”。
三、th:if和th:switch的使用
Thymeleaf還提供了類似於Java中的switch語句的th:switch語法,我們可以配合使用th:case和th:default來實現多條件分支:
<span th:switch="${condition}">
<span th:case="'condition1'" th:text="Condition 1">
<span th:case="'condition2'" th:text="Condition 2">
<span th:default th:text="Unknown Condition">
</span>
上述代碼中,th:switch的值為condition,如果condition為’condition1’,則渲染”Condition 1″;如果condition為’condition2’,則渲染”Condition 2″;如果condition不是任何一個case,則渲染”Unknown Condition”。
四、th:if和th:each的使用
th:each是Thymeleaf用於遍歷集合、數組等的語法,我們可以結合使用th:if來實現根據集合內容的動態渲染:
<ul>
<li th:each="item : ${items}" th:text="${item.name}" th:if="${item.price > 50}"/>
</ul>
上述代碼中,th:each會遍歷items集合,對於每個item,如果item的price大於50,則渲染該item的名字。
五、th:if和th:classappend的使用
使用th:if可以根據一定條件來控制HTML的渲染,我們也可以結合使用th:classappend來動態地為元素添加不同的CSS class:
<div th:classappend="${condition} ? 'success' : 'info'">
This div's class will be success if condition is true, otherwise info.
</div>
以上代碼中,如果condition為true,則渲染div元素,並為其添加success class;否則,渲染div元素,並為其添加info class。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/295163.html