thymeleaf if使用
时间: 2025-06-13 07:13:57 浏览: 14
<think>我们正在讨论Thymeleaf模板引擎中的条件判断用法。用户明确询问了"howtouseifconditioninThymeleaftemplate",因此我们需要提供关于Thymeleaf条件语句的详细指导。回顾之前的对话,用户提到过一些关于SpringBoot配置的弃用键信息,但这与当前问题无关。因此,我们将专注于Thymeleaf的条件判断。在Thymeleaf中,条件判断主要通过以下几种方式实现:1.`th:if`和`th:unless`:用于根据条件显示或隐藏HTML元素。2.使用Elvis运算符进行条件赋值。3.使用三元运算符进行条件表达式求值。4.使用`th:switch`和`th:case`进行多条件分支选择。我们将详细解释每种用法,并给出示例。另外,根据系统指令:-使用中文回答。-在行内数学表达式中使用$...$格式(但本问题可能不涉及数学公式,因此可以忽略)。-生成相关问题。因此,回答结构如下:1.介绍Thymeleaf条件判断的基本概念。2.分别讲解`th:if`/`th:unless`、Elvis运算符、三元运算符、`th:switch`/`th:case`的用法和示例。3.提供完整的示例代码。4.生成相关问题。注意:由于Thymeleaf是HTML模板,所以示例代码应使用HTML标签结合Thymeleaf属性。</think>### Thymeleaf 条件判断(`th:if`/`th:unless`)使用指南
在 Thymeleaf 模板中使用条件判断主要通过以下属性实现:
#### 1. **基础条件判断**
```html
<!-- 当条件为 true 时显示 -->
<div th:if="${condition}">条件成立时显示</div>
<!-- 当条件为 false 时显示 -->
<div th:unless="${condition}">条件不成立时显示</div>
```
**示例**:
```html
<p th:if="${user.isAdmin}">管理员权限</p>
<span th:unless="${product.inStock}">缺货中</span>
```
#### 2. **复杂表达式**
支持逻辑运算符和表达式:
```html
<!-- AND 运算 -->
<div th:if="${age > 18 and country == 'CN'}">成年中国用户</div>
<!-- OR 运算 -->
<span th:if="${status == 'active' or status == 'pending'}">有效状态</span>
<!-- 三元表达式 -->
<p th:text="${user.vip ? '尊享会员' : '普通用户'}"></p>
```
#### 3. **空值安全判断**
使用安全导航运算符 `?.` 避免空指针:
```html
<!-- 当 user.address 不为空时才访问 city -->
<div th:if="${user?.address?.city == 'Beijing'}">北京用户</div>
```
#### 4. **多条件分支 (`th:switch`)**
```html
<div th:switch="${user.role}">
<p th:case="'admin'">系统管理员</p>
<p th:case="'editor'">内容编辑</p>
<p th:case="*">普通用户</p> <!-- 默认分支 -->
</div>
```
#### 5. **结合 HTML 属性**
条件控制属性是否渲染:
```html
<input type="text" th:readonly="${!editable}">
<a th:href="${url}" th:if="${url != null}">访问链接</a>
```
#### ▶️ 完整示例
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:if="${user != null}">
<h2 th:text="'欢迎, ' + ${user.name}"></h2>
<p th:style="${user.vip ? 'color:gold' : 'color:silver'}">
会员状态: <span th:text="${user.vip ? 'VIP' : '普通'}"></span>
</p>
</div>
<div th:unless="${user != null}">
<a href="/login">请先登录</a>
</div>
</body>
</html>
```
### 注意事项
1. **表达式语法**:使用 `${...}` 包裹变量,`*{...}` 用于选择变量
2. **类型自动转换**:非布尔值会自动转换(非空字符串/非零数字 = `true`)
3. **安全导航**:优先用 `?.` 避免空值异常[^1]
---
###
阅读全文
相关推荐
















