1::: 页面模板的使用主要目的是为了页面整体的一致:将header,footer,以及content分为3部分,Content部分的内容用来变更,header,footer部分内容做统一个处理。
踩过的坑:
spring-boot-starter-parent:版本要在1.4.0.RELEASE以上,(因为项目开始的时候用1.3.7,自己尝试了很多办法多没有解决问题,1.idea运行的问题,2.打包成jar发布的问题【idea能够运行成功,并不代表打包成jar也会成功】)
实现梳理:
1.公用部分 footer header
footer.html:
<footer layout:fragment="footer"> <p th:text="'Hello common footer fragment (' + ${name} + ')!'">footer fragment</p> </footer>
header.html:
<header layout:fragment="header"> <p th:text="'Hello common header fragment (' + ${name} + ')!'">header fragment</p></header>
2.模板文件default.html
<header th:replace="fragments/header :: header">
<p>This is default header area for default layout</p>
</header>
<section id="content" layout:fragment="content">
<p th:text="${'Hello ' + name + '!'}"></p>
<p>This is default main content with default layout</p>
</section>
<footer th:replace="fragments/footer :: footer">
<p>This is default footer area for default layout</p>
</footer>
【重点关注:th:replace以及layout:fragment="content"部分内容】
3.需要加载模板的页面文件greeting.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" layout:decorator="layout/default">
<head>
<title>Spring Boot and Thymeleaf - Greeting with Thymeleaf Layout Dialect!</title>
</head>
<body>
<section layout:fragment="content">
<p th:text="${'Hello ' + name + '! Greeting from Thymeleaf Layout Dialect!'}"></p>
<p>This contents from greeting content!</p>
<img src="/images/home.png" />
</section>
</body>
</html>
【重点关注:<html xmlns:th="http://www.thymeleaf.org"layout:decorator="layout/default">以及layout:fragment="content"部分】
5.配置pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
</properties>
6.Java代码以及html内容分布视图
![J2)M{S6_WH`3]MP@F%7OPSR.png](http://upload-images.jianshu.io/upload_images/3420049-d285baf5b7f329ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)