學(xué)習完整課程請移步 互聯(lián)網(wǎng) Java 全棧工程師
這節(jié)主要介紹模板的引入。及如何在不改變前端人員的 HTML 顯示結(jié)果的情況下設(shè)計模板(通過屬性配置動態(tài)時不顯示的部分)。
模板模塊導(dǎo)入
首先定義一個 /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>
不使用 th:fragment 來引用模塊
<div id="copy-section">
© 2018 Copyright by Lusifer.
</div>
我們可以用 CSS 的選擇器寫法來引入
<body>
...
<div th:include="footer :: #copy-section"></div>
</body>
th:include 和 th:replace 的區(qū)別
th:include 和 th:replace 都可以引入模塊,兩者的區(qū)別在于:
-
th:include:引入子模塊的 children,依然保留父模塊的 tag -
th: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>
顯示結(jié)果
<body>
...
<div>
© 2018 Copyright by Lusifer.
</div>
<footer>
© 2018 Copyright by Lusifer.
</footer>
</body>