母版負責頁面主框架,包括導航欄,側邊欄,footer等內容,還有公共css,js的引用.
子頁負責頁面content部分的內容,還可以單獨引用css,js
例子如下:
母版 /templates/admin/dashboard
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <!-- 母版head begin --> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>layout 母版</title>
母版title會被子頁覆蓋 <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" /> <!-- 母版head end -->
子頁head信息會按順序出現在這里 </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" > <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li><a href="#">Menu1</a></li> <li><a href="#">Menu2</a></li> </ul> </div> </div> </nav> <div class="container-fluid"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul class="nav nav-sidebar"> <li class="active"><a href="#">MenuList</a></li> <li><a href="#">Menu1</a></li> <li><a href="#">Menu2</a></li> </ul> </div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main" layout:fragment="content" 子頁定義的東西會被追加到母版容器div上,本例中子頁定義了style會加到這> 母版頁這里可以放些示例內容,反正也會被子頁覆蓋,這里省略了 </div> </div> <div class="row"> <div th:replace="footer :: copy"></div> </div> </div> <script th:src="@{/js/jquery-1.12.4.min.js}"></script> <script th:src="@{/bootstrap-3.3.7-dist/js/bootstrap.min.js}"></script> <th:block layout:fragment="bottomscriptblock">這里是預留給子頁單獨引用js用的,th:block Thymeleaf不會渲染,放代碼塊最合適th:block
is a mere attribute container that allows template developers to specify whichever attributes they want.
Thymeleaf will execute these attributes and then simply make the block dissapear without a trace.
</th:block> </body> </html>
子頁 /templates/admin/dict
如下:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout" layout:decorator="admin/dashboard"> <!-- layout母版頁文件路徑--> <head> <!-- 子頁head,會排在母版頁的后面 <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=Edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> --> <title>子頁title</title> </head> <body>
<div layout:fragment="content" style="width:90%;">子頁這里定義的東西會被添加到母版的div標簽上 <div> 子頁內容 </div> </div> <th:block layout:fragment="bottomscriptblock"> <script th:src="@{/js/holder.min.js}"></script> </th:block>
</body> </html>
子頁的head內信息會按順序出現在母版head信息之后,<title>比較特殊,子頁會覆蓋母版的<title>
子頁單獨需要引用的js,放到底部th:block塊內部.