thymeleaf绑定变量
时间: 2025-06-03 19:17:12 浏览: 13
### Thymeleaf 中绑定变量的示例与用法
在 Thymeleaf 中,绑定变量可以通过多种方式实现,包括但不限于 `th:value`、`th:field` 和表达式语法。以下详细介绍如何在 Thymeleaf 中绑定变量,并提供相关示例。
#### 1. 使用 `th:value` 绑定变量
`th:value` 属性用于将变量的值绑定到 HTML 元素中。例如,在 `<input>` 标签中绑定变量值:
```html
<input type="text" th:value="${user.name}" />
```
上述代码将 Java 后端传递的 `user.name` 值绑定到输入框的 `value` 属性中[^5]。
#### 2. 使用 `th:field` 实现双向绑定
`th:field` 是 Thymeleaf 提供的一种强大的双向绑定机制,主要用于表单字段。它不仅设置值,还负责处理表单提交时的数据回传。
示例:
```html
<form th:object="${user}">
<input type="text" th:field="*{name}" />
</form>
```
在这个例子中,`th:object="${user}"` 将整个 `user` 对象绑定到表单,而 `th:field="*{name}"` 则绑定 `user` 对象的 `name` 属性[^5]。
#### 3. 在 URL 中绑定变量
Thymeleaf 支持通过 `@{}` 表达式构造动态 URL,并绑定变量。例如:
```html
<a th:href="@{/user/profile(id=${userId})}">用户资料</a>
```
此代码生成一个链接,其中 `id` 参数会被替换为后端传递的 `userId` 值[^2]。
#### 4. 在文本中绑定变量
使用 `th:text` 或直接嵌入表达式可以在页面上显示变量值:
```html
<p th:text="'用户名:' + ${user.name}"></p>
```
或者更简洁的方式:
```html
<p>用户名:[[${user.name}]]</p>
```
这两种方式都可以将 `user.name` 的值插入到段落中[^4]。
#### 5. 条件绑定变量
通过 `th:if` 或三元运算符可以实现条件绑定。例如:
```html
<div th:if="${user.type == 'admin'}">
管理员专用功能
</div>
<span th:text="${user.type == 'admin' ? '管理员' : '普通用户'}"></span>
```
上述代码根据 `user.type` 的值显示不同的内容[^4]。
#### 6. 遍历集合并绑定变量
使用 `th:each` 可以遍历集合并将每个元素绑定到模板中:
```html
<ul>
<li th:each="item : ${items}" th:text="${item.name}"></li>
</ul>
```
这段代码会为集合 `items` 中的每个元素生成一个列表项,并显示其 `name` 属性[^4]。
---
### 注意事项
- 确保后端控制器正确地将数据模型传递给 Thymeleaf 模板。
- 如果需要格式化日期或数字,可以使用内置工具如 `#dates` 或 `#numbers`[^3]。
---
### 示例代码总结
以下是一个完整的 Thymeleaf 表单绑定示例:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf 变量绑定示例</title>
</head>
<body>
<form th:object="${user}" method="post">
<label>姓名:</label>
<input type="text" th:field="*{name}" /><br />
<label>年龄:</label>
<input type="number" th:field="*{age}" /><br />
<button type="submit">提交</button>
</form>
<p th:text="'欢迎您,' + ${user.name}"></p>
</body>
</html>
```
---
阅读全文
相关推荐


















