开头奉上官方文档(http://www.thymeleaf.org/doc/articles/layouts.html)!
博主在整合前台页面整体布局的时候发现 layout:fragment 使用不了,查了一个多小时资料,才发现要引入一个包,下面奉上maven引入(建议在整合thymeleaf的时候顺便一起把这个依赖下载下来!!!!):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency> <!-- thymeleaf依赖-->
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
<version>2.2.1</version> <!-- dialect依赖-->
</dependency>
下面开始创建模板(建立如下文件):
下面贴上代码:
footer.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<div th:fragment="footer">
这是一个底部
</div>
</body>
</html>
left.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
</head>
<body>
<div th:fragment="left" >
这是个左侧
</div>
</body>
</html>
layout.html(整合之前的footer和left),这里我们有三种标签可以使用:th:insert/th:replace/th:include(thymeleaf3.0之后不推荐使用):
这里简单说下这三个的区别:(参考博客( thymeleaf th:replace th:include th:insert 的区别
))
th:insert :保留自己的主标签,保留th:fragment的主标签。
th:replace :不要自己的主标签,保留th:fragment的主标签。
th:include :保留自己的主标签,不要th:fragment的主标签。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div th:replace="pagetemplate/footer :: footer"></div>
<div layout:fragment="content"></div>
<div th:replace="pagetemplate/left :: left"></div>
</body>
</html>
这样我们的一个基础模板就创建好了,接下来在我们页面中引用:
login.html
layout:decorator 标签 的作用是 寻找我们的模板文件 (默认路径是templates/)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="layout">
<head>
<title>登录页面</title>
<link th:href="@{/bootstrap/bootstrap.min.css}" rel="stylesheet">
</head>
<body>
<div layout:fragment="content">
<div class="container-fluid">
<div class="row">
<div>
<input type="text" class="form-control col-sm-12" placeholder="请输入账号名"/>
<input type="password" class="form-control col-sm-12" placeholder="请输入密码"/>
</div>
</div>
</div>
</div>
<script th:src="@{/jquery/jquery-3.3.1.min.js}"></script>
</body>
</html>
代码链接:
https://download.youkuaiyun.com/download/lib_dil/10282533