在springboot中使用thymeleaf的组件(fragment)
目的:抽取公共部分,节省代码量
创建springboot项目
过程略
项目结构如下
添加thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
修改application.properties
配置
# thymeleaf
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=UTF-8
在templates中创建html页面和文件夹
分别创建index.html
和component
文件夹![在这里插入图片描述](https://img-blog.csdnimg.cn/20210610171443916.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTk5OTU5NA==,size_16,color_FFFFFF,t_70)
在html页面中添加约束
xmlns:th="http://www.thymeleaf.org"
在component
目录中创建commons.html
文件
使用th:fragment
属性定义组件:th:fragment="<组件名>"
<div th:fragment="headnav">
headnav
</div>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<!--headernav-->
<div th:fragment="headnav">
headnav
</div>
<!--footer-->
<div th:fragment="footer">
footer
</div>
</html>
在其他页面中进行引用
需要正确的路径,这里以th:replaceth
为例:replace="~{component/commons::headnav}"
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:replace="~{component/commons::headnav}"></div>
hello thymeleaf~
<div th:replace="~{component/commons::footer}"></div>
</body>
</html>
启动项目查看效果
打开浏览器,输入http://localhost:8080/
可以看到,成功抽取和引入了thymeleaf的组件。