本文章來自【知識林】
本文章主要講述使用Thymeleaf做頁面模板,頁面模板的主要作用是將相對公共的頁面部份(如站頭、站尾及公共的js、css等)提取出現放到模板頁面中,在其他需要使用的地方引用該模板即可。
如果對Thymeleaf的基本使用、maven依賴等不清楚的可以先閱讀我的另一篇文章《Thymeleaf 之 初步使用》。
- application.properties
server.port = 1104
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.cache=false
- Controller
@Controller
public class IndexController {
@GetMapping(value = "/index")
public String index(Model model, HttpServletRequest request) {
return "/web/index";
}
}
- 頁面模板webModel.html
<!DOCTYPE html>
<html lang="zh-CN"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf學習示例</title>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<script type="text/javascript" src="/jquery-1.12.3.min.js"></script>
<script type="text/javascript" src="/bootstrap3/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="/bootstrap3/css/bootstrap.min.css"/>
</head>
<body>
<div class="container text-center" style="text-align:center;border:1px #3b8cff solid;">
<h3>頭部</h3>
</div>
<div class="container-fluid center-container" style="margin-bottom:70px;">
<div th:include="this :: content"></div>
</div>
<div class="navbar navbar-default navbar-fixed-bottom" role="navigation">
<div class="container text-center login-bottom">
© 2016
</div>
</div>
</body>
</html>
注意:
1. 需要使用Thymeleaf的命名空間`xmlns:th="http://www.thymeleaf.org"`
2. 本示例使用了`bootstrap`的知識,如有不清楚的可上[官網](http://v3.bootcss.com)學習或直接忽略。
3. 最關鍵部份:`<div th:include="this :: content"></div>`使用`th:include`來將數據引入進來。
意爲將`content`部份的內容引入到這個地方,`content`是在具體頁面中體現,此名稱可自己定義。
- 頁面index.html
<!DOCTYPE html>
<html lang="zh-CN"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="fragments/webModel">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>測試首頁</title>
</head>
<body>
<div th:fragment="content" th:remove="tag">
<h2>這裏顯示專屬本頁面的內容</h2>
</div>
</body>
</html>
注意:
1. 需要引入Thymeleaf的命名空間:`xmlns:th="http://www.thymeleaf.org"`
2. 需要引入佈局layout的命名空間:`xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"`
3. 指定引用的模板名稱:`layout:decorator="fragments/webModel"`(名稱即爲html頁面名稱)
3. 使用`th:fragment="content"`來啓用頁面模板,啓用的模板根據模板名稱和fragment名稱而定。
`content`是根據`webModel.html`頁面模板中指定的名稱而定。
4. 這裏使用了`th:remove="tag"`這表示數據加載完成後將當前標題刪除。
示例代碼:https://github.com/zsl131/thymeleaf-study/tree/master/study04
本文章來自【知識林】