Thymeleaf - 现代服务器端 Java 模板引擎

Thymeleaf - 现代服务器端 Java 模板引擎

1. 什么是 Thymeleaf?

Thymeleaf 是一个现代的、服务器端的 Java 模板引擎,它能够处理 HTML、XML、JavaScript、CSS 甚至纯文本。最重要的是,它可以在浏览器中直接打开且显示正确的模板页面,因为它支持自然模板。

2. 主要特点

  • 自然模板:模板文件即使不通过服务器运行,也能在浏览器中正确显示
  • 与 Spring 框架完美集成
  • 强大的方言扩展机制
  • 优秀的 IDE 支持

3. 基本语法示例

3.1 标准表达式

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

<!-- 选择表达式 -->
<div th:object="${user}">
    <p th:text="*{name}">默认名称</p>
    <p th:text="*{age}">0</p>
</div>

<!-- URL 表达式 -->
<a th:href="@{/user/profile(id=${user.id})}">查看资料</a>

3.2 条件判断

<!-- if 条件 -->
<p th:if="${user.age > 18}">成年人</p>

<!-- unless 条件(相当于 if 的反面) -->
<p th:unless="${user.age > 18}">未成年人</p>

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

4. 在 Spring Boot 中使用 Thymeleaf

4.1 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

4.2 配置示例

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

5. 常用功能

5.1 循环遍历

<table>
    <tr th:each="user : ${users}">
        <td th:text="${user.name}">姓名</td>
        <td th:text="${user.age}">年龄</td>
    </tr>
</table>

5.2 字符串处理

<!-- 字符串拼接 -->
<p th:text="'Welcome, ' + ${user.name} + '!'">Welcome!</p>

<!-- 数字格式化 -->
<p th:text="${#numbers.formatDecimal(price, 1, 2)}">0.00</p>

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

6. 最佳实践

  1. 使用片段(Fragment):将重复使用的代码块抽取为片段
<!-- 定义片段 -->
<footer th:fragment="copy">
    &copy; 2024 我的网站
</footer>

<!-- 使用片段 -->
<div th:insert="~{footer :: copy}"></div>
  1. 使用布局:创建统一的页面布局模板
  2. 合理使用缓存:生产环境开启缓存以提高性能
  3. 保持模板简洁:避免在模板中编写复杂的业务逻辑

7. 总结

Thymeleaf 作为一个现代化的模板引擎,不仅提供了强大的功能,还保持了良好的可维护性。它与 Spring Boot 的完美集成使其成为 Java Web 开发中的首选模板引擎之一。通过合理使用其特性,可以大大提高开发效率和代码质量。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容