th:if详解

发布时间:2023-05-16

一、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:textth: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:caseth: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,如果itemprice大于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。