Thymeleaf 模板布局

學(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">
            &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 引入自身模板的模塊

上面所有的 templatenamedomselector 的寫法都支持表達式寫法:

<div th:include="footer :: (${user.isAdmin}? #{footer.admin} : #{footer.normaluser})"></div>

不使用 th:fragment 來引用模塊

<div id="copy-section">
&copy; 2018 Copyright by Lusifer.
</div>

我們可以用 CSS 的選擇器寫法來引入

<body>
...
<div th:include="footer :: #copy-section"></div>
</body>

th:includeth:replace 的區(qū)別

th:includeth:replace 都可以引入模塊,兩者的區(qū)別在于:

  • th:include:引入子模塊的 children,依然保留父模塊的 tag
  • th:replace:引入子模塊的所有,不保留父模塊的 tag

舉個例子

<footer th:fragment="copy">
&copy; 2018 Copyright by Lusifer.
</footer>

引入界面

<body>
...
<div th:include="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
</body>

顯示結(jié)果

<body>
...
<div>
&copy; 2018 Copyright by Lusifer.
</div>
<footer>
&copy; 2018 Copyright by Lusifer.
</footer>
</body>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容