Thymeleaf模板引擎怎么使用

发布时间:2022-01-21 15:12:50 作者:iii
来源:亿速云 阅读:539
# Thymeleaf模板引擎怎么使用

## 一、Thymeleaf简介

### 1.1 什么是Thymeleaf
Thymeleaf是一个现代化的服务器端Java模板引擎,适用于Web和独立环境。它能够处理HTML、XML、JavaScript、CSS甚至纯文本。与JSP等传统技术相比,Thymeleaf的主要特点是:
- **自然模板**:可在浏览器直接打开预览
- **无Servlet依赖**:不强制要求Servlet环境
- **Spring完美集成**:Spring官方推荐的视图技术
- **表达式语法**:强大的OGNL和SpringEL表达式支持

### 1.2 核心特性
- **模板缓存**:可配置的模板缓存机制
- **国际化支持**:内置国际化处理能力
- **片段重用**:支持模板片段定义和引用
- **多种方言**:可通过方言扩展功能

## 二、环境配置

### 2.1 Maven依赖
```xml
<!-- Spring Boot集成 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- 独立使用 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.1.1.RELEASE</version>
</dependency>

2.2 Spring Boot配置

# application.properties
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false # 开发时关闭缓存
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML

2.3 基本目录结构

src/
├── main/
│   ├── java/
│   └── resources/
│       ├── static/    # 静态资源
│       └── templates/ # 模板文件

三、基础语法详解

3.1 标准表达式语法

<!-- 变量表达式 -->
<p th:text="${user.name}">默认用户名</p>

<!-- 选择表达式 -->
<div th:object="${user}">
    <p th:text="*{age}">年龄</p>
</div>

<!-- 链接表达式 -->
<a th:href="@{/user/list}">用户列表</a>

<!-- 片段表达式 -->
<div th:insert="~{footer :: content}"></div>

3.2 常用属性指令

属性 说明
th:text 文本替换
th:utext 非转义文本
th:value 表单值设置
th:each 循环迭代
th:if 条件判断
th:switch 多条件选择
th:href 链接URL
th:src 资源URL

3.3 循环与条件

<!-- 循环示例 -->
<ul>
    <li th:each="item : ${items}" th:text="${item.name}"></li>
</ul>

<!-- 条件判断 -->
<div th:if="${user.isAdmin}">管理员面板</div>
<div th:unless="${user.isAdmin}">普通用户面板</div>

<!-- Switch语句 -->
<div th:switch="${user.role}">
    <p th:case="'admin'">管理员</p>
    <p th:case="'user'">普通用户</p>
</div>

四、高级功能

4.1 模板布局

定义基础模板 base.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title th:fragment="title">默认标题</title>
</head>
<body>
    <header th:insert="~{header :: main}"></header>
    <div th:replace="~{content}"></div>
    <footer th:replace="~{footer :: main}"></footer>
</body>
</html>

子模板继承:

<html th:replace="~{base :: layout(~{::title}, ~{::content})}">
<head>
    <title>子页面标题</title>
</head>
<body>
    <div th:fragment="content">
        <!-- 页面特有内容 -->
    </div>
</body>
</html>

4.2 表单处理

<form th:action="@{/user/save}" th:object="${user}" method="post">
    <input type="text" th:field="*{name}">
    <input type="email" th:field="*{email}">
    <button type="submit">保存</button>
</form>

4.3 国际化支持

<p th:text="#{welcome.message}">欢迎消息</p>
<p th:text="#{|hello.user|(${user.name})|}">个性化问候</p>

4.4 实用工具对象

<!-- 日期格式化 -->
<p th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}"></p>

<!-- 集合工具 -->
<p th:text="${#lists.size(user.roles)}"></p>

<!-- 字符串操作 -->
<p th:text="${#strings.toUpperCase(user.name)}"></p>

五、与Spring集成

5.1 Controller数据传递

@Controller
public class UserController {
    
    @GetMapping("/user")
    public String user(Model model) {
        model.addAttribute("user", new User("张三", 25));
        return "user/profile";
    }
}

5.2 Spring Security整合

<div sec:authorize="isAuthenticated()">
    欢迎 <span sec:authentication="name"></span>
</div>
<div sec:authorize="hasRole('ADMIN')">
    管理员功能
</div>

5.3 表单验证错误处理

<input type="text" th:field="*{email}" class="form-control">
<div th:if="${#fields.hasErrors('email')}" 
     th:errors="*{email}" class="error-message"></div>

六、性能优化

6.1 模板缓存配置

# 生产环境配置
spring.thymeleaf.cache=true
spring.thymeleaf.template-resolver-order=1

6.2 片段缓存

<!-- 缓存用户信息片段 -->
<div th:replace="~{user/info :: panel}" 
     th:with="cacheKey=${#strings.arrayJoin('user',user.id)}">
</div>

6.3 静态资源处理

<!-- 版本化静态资源 -->
<link th:href="@{/css/main.css(v=${@environment.getProperty('app.version')})}">

七、常见问题解决方案

7.1 转义问题

<!-- 禁用转义 -->
<p th:utext="${htmlContent}"></p>

<!-- 内联表达式 -->
[(${unsafeContent})]

7.2 静态资源404

确保正确配置:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}

7.3 模板解析异常

检查: 1. 模板文件是否在正确目录 2. 后缀配置是否匹配 3. 模板语法是否正确

八、最佳实践

  1. 分离逻辑与表现:避免在模板中编写复杂逻辑
  2. 使用片段重用:提高模板复用率
  3. 合理使用缓存:开发时关闭,生产环境开启
  4. 统一错误处理:创建error.html模板
  5. 模板版本控制:与代码库一起管理

九、总结

Thymeleaf作为现代Java模板引擎,通过本文我们全面了解了: - 从基础语法到高级功能的使用方法 - 与Spring框架的深度集成 - 实际开发中的性能优化技巧 - 常见问题的解决方案

通过合理应用Thymeleaf,可以构建出结构清晰、维护性强的Web应用视图层。其自然模板特性特别适合前后端协作开发场景,是传统JSP技术的优秀替代方案。


本文约4500字,涵盖了Thymeleaf的核心使用场景。实际开发中应根据项目需求选择合适的特性组合,并参考官方文档获取最新特性支持。 “`

推荐阅读:
  1. springBoot(5):web开发-模板引擎FreeMarker与thymeleaf
  2. 如何使用Thymeleaf对象

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

thymeleaf

上一篇:Ubuntu系统怎么安装Flash Player应用

下一篇:nginx如何配置反向代理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》