1、依赖配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、基础配置
application.properties文件配置中
spring.thymeleaf.cache = true #启动模板缓存
spring.thymeleaf.encoding = UTF-8 #模板编码
spring.thymeleaf.mode = HTML5 #应用于模板的模板模式
spring.thymeleaf.prefix = classpath:/templates/ #指定模板页面存放路径
spring.thymeleaf.suffix = .html #指定模板
3、html引入模板引擎
<html xmlns:th="http://www.thymeleaf.org">
上述用于引入thymeleaf模版引擎标签。
使用关键字“th”标注的标签是Thymeleaf模版提供的标签。
例1:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
<title>Title</title>
</head>
<body>
<p th:text="${hello}">欢迎进入Thymeleaf的学习</p>
</body>
</html>
4、常用标签
| th: 标签 | 说明 |
|---|---|
| th:insert | 布局标签,替换内容到引入的文件,例3 |
| th:replace | 页面片段包含(类似JSP中的include标签),例2 |
| th:each | 元素遍历(类似JSP中的c:foreach标签),例2 |
| th:if | 条件判断,如果为真 |
| th:unless | 条件判断,如果为假 |
| th:switch | 条件判断,进行选择性匹配,例2 |
| th:case | 条件判断,进行选择性匹配,例2 |
| th:value | 属性值修改,指定标签属性值 |
| th:href | 用于设定链接地址 |
| th:src | 用于设定链接地址 |
| th:text | 用于指定标签显示的文本内容 |
例2
header.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
th:fragment="header(title,keywords)">
......
</html>
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 载入文章头部页面,位置在/client文件夹下的header模板页面,模板名称th:fragment为header -->
<div th:replace="/client/header::header(null,null)"/>
<body>
<div th:each="item : ${list}">
<!-- ${item.enable}可以直接用*{enable} -->
<div th:switch="${item.enable}">
<p th:case="1">
......
</p>
<p th:case="0">
......
</p>
</div>
</div>
</body>
</html>
5、标准表达式
| 说明 | 表达式语法 |
|---|---|
| 变量表达式 | ${…} |
| 选择变量表达式(java对象属性,与上面${}连用),例2 | *{…} |
| 消息表达式(用于国际化设置) | #{…} |
| 链接URL表达式,例1 | @{…} |
| 片段表达式,例3 | ~{…} |
例3
片段表达式~{},用来标记一个片段模版,并根据需要移动或传递给其他模版。其中,最常见的用法是使用th:insert或th:replace属性插入片段。
<div th:insert="~{thymeleafDemo::title}"></div>
6、变量表达式 ${…}中的内置对象
#ctx 上下文对象
#vars 上下文变量
#locale 上下文区域设置
#request (仅限Web Context)HttpServletRequest对象
#response (仅限Web Context)HttpServletResponse对象
#session (仅限Web Context)HttpSession对象(注:最初使用时记得在controller的相应handle中添加session参数,否则sessen对象没有实例化,为空)
#servletContext (仅限Web Context)ServletContext对象
文章内容输出来源:拉勾教育Java高薪训练营

本文介绍如何在Spring Boot项目中配置并使用Thymeleaf模板引擎,涵盖依赖配置、基础配置、HTML引入方法及常用标签等核心内容。
516

被折叠的 条评论
为什么被折叠?



