Skip to content

1. 简介

Thymeleaf 适用于 Web 和单机的现代服务器端 Java 模板引擎

  • 主要目的是给人们带来优雅 自然模板 至您的开发工作流,可以在浏览器中正确显示的 HTML 还可以用作静态原型,从而实现更强的协作在开发团队中

2. 添加依赖

xml
<!-- START: thymeleaf 模板引擎 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- END: thymeleaf 模板引擎 -->

3. 配置模板引擎

默认情况下,Spring Boot 会自动创建配置 Thymeleaf, 可以自定义配置在 application.yaml 配置文件中配置修改。

yaml
# Thymeleaf 模板引擎配置
spring:  
  thymeleaf: 
    # 文件后后缀路径
    prefix: classpath:/templates/ // [!code focus]
    # 文件后缀添加 .html
    suffix: .html // [!code focus]

4. 配置模板

resource 文件夹下创建一个 templates 文件夹用于存放相应 html。

  • 创建: 一个 index.html
html
<!DOCTYPE html>
<html xmlns:xmlsn="http://www.w3.org/1999/xhtml" xmlsn:th="https://www.thymeleaf.org">
  <head>
    <title>Spring Boot Thymeleaf Example</title>
  </head>

  <body>
    <h1 th:text="${message}">Hello Wold !</h1>
  </body>
</html>

5. 编写控制器

  • 新建一个 IndexController
java
package com.calvin.spring.boot.example.thymeleaf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 首页-控制器
 *
 * @author Calvin
 * @date 2024/2/4
 * @since v1.0.0
 */
@Controller
@RequestMapping
public class IndexController {

    @GetMapping("")
    public String index(Model model){
        // 给 index.html 页面中的 H1 标题赋变量值
        model.addAttribute("message", "首页");  
        // 因为配置文件配置了 "suffix: .html", 所以只要链接对应页面就会跳转
        return "index";   
    }

}
  • 访问浏览器,页面展示如下:

6. Thymeleaf 语法和组件

组件

th属性: 执行的优先级从 1~8,数字越低优先级越高。

  • th:text: 设置当前元素的文本内容, order=7
  • th:value: 设置当前元素的value值, order=6
html
<body>
  <h1>this is success.html</h1>
  <!-- th:text 设置当前元素的文本内容,常用,优先级不高 -->
  <p th:text="${msg}"></p>
  <p th:utext="${msgUtext}"></p>

  <!-- th:value 设置当前元素的value值,常用,优先级仅比th:text高 -->
  姓名:
  <input type="text" th:value="${emp.name}" />
  年龄:
  <input type="text" th:value="${emp.age}" />
</body>
  • th:each: 遍历循环元素, 和 th:textth:value 一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2
    • index:列表状态的序号,从 0 开始;
    • count:列表状态的序号,从 1 开始;
    • size:列表状态,列表数据条数;
    • current:列表状态,当前数据对象;
    • even:列表状态,是否为奇数,boolean 类型;
    • odd:列表状态,是否为偶数,boolean 类型;
    • first:列表状态,是否为第一条,boolean 类型;
    • last:列表状态,是否为最后一条,boolean 类型;
html
<body>
  <h1>this is success.html</h1>

  <!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入,遍历被修饰的元素-->
  <table border="1px" th:width="200px">
    <thead>
      <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr th:each="e:${emps}">
        <td>编号</td>
        <td th:text="${e.name}"></td>
        <td th:text="${e.age}"></td>
        <td>删除/修改</td>
      </tr>
    </tbody>
    <tbody>
      <!-- 说明:th:each="e,eState : ${emps}" 其中e为循环的每一项,eState是下标属性(可省略),eState属性包括:-->
      <tr th:each="e,eState:${emps}">
        <td th:text="${eState.index+1}"></td>
        <td th:text="${e.name}"></td>
        <td th:text="${e.age}"></td>
        <td>删除/修改</td>
      </tr>
    </tbody>
  </table>
</body>
  • th:if: 条件判断, 类似的还有 th:unless,th:switch,th:case。优先级较高:order=3
    • gt:great than(大于)
    • ge:great equal(大于等于)
    • eq:equal(等于)
    • lt:less than(小于)
    • le:less equal(小于等于)
    • ne:not equal(不等于)
html
<!--th:if 条件判断,类似的有th:switch,th:case,优先级仅次于th:each,-->
<p th:text="${map.Boss.name}" th:if="${map.Boss.age gt 20}"></p>
  • th:insert: 代码块引入, 类似的还有th:replaceth:include,三者的区别较大,若使用不恰当会破坏 html 结构,常用于公共代码块提取的场景。优先级最高:order=1
  • th:fragment: 定义代码块, 定义代码块,方便被 th:insert引用。优先级最低:order=8
  • th:object: 声明变量, 声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4
  • th:attr: 修改任意属性, 修改任意属性,实际开发中用的较少,因为有丰富的其他 th 属性帮忙,类似的还有th:attrappendth:attrprepend。优先级一般:order=5

语法

功能:

  • 获取对象的属性和方法
  • 可以使用 ctx,vars,locale,request,response,session,servletContext内置对象
  • 可以使用 dates,numbers,strings,objects,arrays,lists,sets,maps等内置方法