概述
模板模塊導入
首先定義一個 /resources/templates/footer.html
文件:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="copy">
© 2018 Copyright by Lusifer.
</div>
</body>
</html>
上面的代碼定義了一個片段稱爲 copy
,我們可以很容易地使用 th:include
或者 th:replace
屬性包含在我們的主頁上
<body>
<div th:include="footer :: copy"></div>
</body>
include
的表達式相當簡潔。這裏有三種寫法:
templatename::domselector
或者templatename::[domselector]
引入模板頁面中的某個模塊templatename
引入模板頁面::domselector
或者this::domselector
引入自身模板的模塊
上面所有的 templatename
和 domselector
的寫法都支持表達式寫法:
<div th:include="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>
不使用 fragment 來引用模塊
<div id="copy-section">
© 2018 Copyright by Lusifer.
</div>
我們可以用 CSS 的選擇器寫法來引入
<body>
<div th:include="footer :: #copy-section"></div>
</body>
include 和 replace 的區別
th:include
和 th:replace
都可以引入模塊,兩者的區別在於:
th:include
:引入子模塊的 children,依然保留父模塊的 tagth:replace
:引入子模塊的所有,不保留父模塊的 tag
舉個例子
<footer th:fragment="copy">
© 2018 Copyright by Lusifer.
</footer>
引入界面
<body>
<div th:include="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
</body>
顯示結果
<body>
<div>
© 2018 Copyright by Lusifer.
</div>
<footer>
© 2018 Copyright by Lusifer.
</footer>
</body>