# Thymeleaf模板的使用方法 ## 一、Thymeleaf简介 ### 1.1 什么是Thymeleaf Thymeleaf是一款现代化的服务器端Java模板引擎,适用于Web和独立环境。它能够处理HTML、XML、JavaScript、CSS甚至纯文本,主要面向Web应用的视图层开发。 ### 1.2 核心特点 - **自然模板**:可在浏览器直接打开预览,无需启动服务 - **语法优雅**:采用标准HTML5标签属性扩展 - **强类型支持**:与Spring框架深度集成 - **模块化设计**:支持多种模板模式 - **国际化支持**:内置国际化处理机制 ## 二、环境配置 ### 2.1 Spring Boot集成 ```xml <!-- Maven依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
# application.yml配置示例 spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML encoding: UTF-8 cache: false # 开发时建议关闭缓存
<p th:text="${user.name}">默认用户名</p>
<div th:object="${session.user}"> <p>姓名: <span th:text="*{name}"></span></p> </div>
<h1 th:text="#{header.title}">默认标题</h1>
<a th:href="@{/user/list(page=1,size=10)}">用户列表</a>
<div th:insert="~{commons :: header}"></div>
属性 | 说明 |
---|---|
th:text | 文本替换 |
th:utext | 非转义文本 |
th:value | 表单值绑定 |
th:each | 循环迭代 |
th:if | 条件判断 |
th:switch | 选择结构 |
th:href | 链接地址 |
th:src | 资源路径 |
th:class | CSS类控制 |
<form th:action="@{/user/save}" th:object="${user}" method="post"> <input type="text" th:field="*{username}"> <input type="password" th:field="*{password}"> <button type="submit">保存</button> </form>
<div th:switch="${user.role}"> <p th:case="'admin'">管理员用户</p> <p th:case="*">普通用户</p> </div>
<table> <tr th:each="user,stat : ${users}"> <td th:text="${stat.index}">序号</td> <td th:text="${user.name}">姓名</td> <td th:text="${user.age}">年龄</td> </tr> </table>
base.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title th:fragment="title">默认标题</title> </head> <body> <div th:replace="~{fragments/header :: main-header}"></div> <section th:insert="~{::content}">默认内容</section> <div th:replace="~{fragments/footer :: main-footer}"></div> </body> </html>
page.html
<html th:replace="~{layouts/base :: layout(~{::title},~{::content})}"> <head> <title>页面标题</title> </head> <body> <section th:fragment="content"> <!-- 页面特有内容 --> </section> </body> </html>
th:block
作为逻辑容器<!-- 防止XSS --> <p th:text="${unsafeContent}"></p> <!-- 谨慎使用非转义内容 --> <p th:utext="${trustedHtml}"></p>
<!-- 调试输出 --> <div th:text="${#ctx}"></div> <!-- 模板注释 --> <!--/* 这段代码仅服务端可见 */-->
<!-- 正确引用方式 --> <link th:href="@{/css/style.css}" rel="stylesheet"> <script th:src="@{/js/app.js}"></script>
<span th:text="${#dates.format(user.createDate, 'yyyy-MM-dd')}"></span>
<div th:if="${#lists.isEmpty(users)}">暂无数据</div>
public class MyDialect extends AbstractProcessorDialect { // 实现自定义标签和属性 }
<div id="app" th:inline="javascript"> var app = new Vue({ data: { message: [[${vueMessage}]] } }); </div>
Thymeleaf作为现代Java模板引擎,通过其优雅的语法设计和强大的功能集成,已成为Spring生态中视图层技术的首选方案。掌握其核心用法后,开发者可以: 1. 快速构建动态页面 2. 实现优雅的模板复用 3. 轻松处理国际化需求 4. 与前后端技术无缝集成
随着Spring Boot的持续流行,Thymeleaf的应用前景将更加广阔。
注:本文档基于Thymeleaf 3.x版本,部分语法与2.x版本存在差异。 “`
(全文约4980字,可根据需要扩展具体章节的详细内容)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。