Thymeleaf 模板佈局

概述

模板模塊導入

首先定義一個 /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>

不使用 fragment 來引用模塊

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

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

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

include 和 replace 的區別

th:includeth:replace 都可以引入模塊,兩者的區別在於:

  • 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>

顯示結果

<body>
    <div>
    	&copy; 2018 Copyright by Lusifer.
    </div>
    <footer>
    	&copy; 2018 Copyright by Lusifer.
    </footer>
</body>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章