一、Thymeleaf判斷相等
Thymeleaf提供了兩種方式來判斷相等,分別是使用eq和==。
使用eq:
<p th:text="${name eq 'Tom'}"></p>
如果name等於Tom,輸出true;否則輸出false。
使用==:
<p th:text="${name == 'Tom'}"></p>
使用==,如果name等於Tom,輸出true;否則輸出false。
二、Thymeleaf變量
在Thymeleaf中,可以使用變量來進行數據的傳遞。
比如,我們在控制器中定義了一個user對象:
User user = new User();
user.setName("Tom");
model.addAttribute("user", user);
在頁面中,我們可以通過th:object來引用這個對象,然後通過th:text來輸出其中的屬性:
<div th:object="${user}">
<p th:text="name"></p>
</div>
三、Thymeleaf判斷不佔位置
在Thymeleaf中,可以使用th:if語句來進行判斷,同時不佔用頁面的位置。
<div th:if="${name eq 'Tom'}">
<p>Hello, Tom!</p>
</div>
如果name等於Tom,顯示Hello, Tom!,否則不顯示任何內容。
四、Thymeleaf判斷一個對象為空
可以使用th:if與th:unless對對象進行判斷是否為空。
<div th:if="${user == null}">
<p>當前用戶為空</p>
</div>
<div th:unless="${user == null}">
<p>當前用戶為<span th:text="${user.name}"></span></p>
</div>
如果user為空,顯示當前用戶為空;否則顯示當前用戶為user.name。
五、Thymeleaf判斷集合
在Thymeleaf中,可以使用th:each對集合進行遍歷,同時可以使用th:if對元素進行判斷。
<div th:each="user: ${users}">
<div th:if="${user.gender == 'male'}">
<p th:text="${user.name} + ' is a male.'"></p>
</div>
<div th:if="${user.gender == 'female'}">
<p th:text="${user.name} + ' is a female.'"></p>
</div>
</div>
使用th:if判斷user.gender的值,如果為male,輸出user.name + ' is a male.',否則輸出user.name + ' is a female.'。
六、Thymeleaf判斷是否為字符串類型
可以使用th:if與th:unless判斷變量是否為字符串類型。
<div th:if="${name.getClass().getName() == 'java.lang.String'}">
<p>${name}是字符串類型</p>
</div>
<div th:unless="${name.getClass().getName() == 'java.lang.String'}">
<p>${name}不是字符串類型</p>
</div>
七、Thymeleaf判斷是否為浮點數類型
可以使用th:if與th:unless判斷變量是否為浮點數類型。
<div th:if="${price.getClass().getName() == 'java.lang.Float'}">
<p>${price}是浮點數類型</p>
</div>
<div th:unless="${price.getClass().getName() == 'java.lang.Float'}">
<p>${price}不是浮點數類型</p>
</div>
八、Thymeleaf判斷是否為數字
可以使用th:if與th:unless判斷變量是否為數字。
<div th:if="${price.getClass().getName() == 'java.lang.Integer' || price.getClass().getName() == 'java.lang.Double'}">
<p>${price}是數字類型</p>
</div>
<div th:unless="${price.getClass().getName() == 'java.lang.Integer' || price.getClass().getName() == 'java.lang.Double'}">
<p>${price}不是數字類型</p>
</div>
九、Thymeleaf判斷某一個key存在
可以使用th:if與th:unless判斷某個key是否存在。
<div th:if="${user.containsKey('name')}">
<p>${name}存在</p>
</div>
<div th:unless="${user.containsKey('name')}">
<p>${name}不存在</p>
</div>
十、Thymeleaf判斷登錄用戶的角色
可以在控制器中定義一個role變量,然後在頁面中使用th:switch語句來判斷用戶角色:
<div th:switch="${role}">
<p th:case="'admin'">您是管理員</p>
<p th:case="'user'">您是普通用戶</p>
<p th:case="'guest'">您是遊客</p>
</div>
以上就是Thymeleaf判斷的詳細內容,不同的判斷方式可以根據實際需要進行選擇。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/160800.html
微信掃一掃
支付寶掃一掃