一、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。