thymeleaf layout 原

thymeleaf是spring boot默認的模板引擎,屬於比較新的模板引擎,這個提供了很多新功能,頁面就是原生的html頁面,並且通過標籤的方式能徹底的進行前後端分離。通常的時候不管是管理系統還是網站系統,總會有很多共用的部分,例如header和footer等等。
如果使用的是springboot 1.5.9版本,則它內置的thymeleaf版本是1.4.2,在官網上可以看到,現在thymeleaf都都已經升級到了3.0版本,對於layout佈局的這種,3.0支持insert標籤。

更改thymeleaf版本

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!-- set thymeleaf version -->
        <thymeleaf.version>3.0.0.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.0.0</thymeleaf-layout-dialect.version>
    </properties>

使用 replace

根據官網的例子,我們有一個文件footer.html文件,這個文件位於 layout文件夾下,代碼如下

<!DOCTYPE html>\
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="copy">
    &copy; 2011 The Good Thymes Virtual Grocery
</div>
</body>
</html>

然後在另外一個頁面中引用

<div th:replace="layout/footer::copy"></div>

這樣就把剛纔的footer頁面引用進來了.
當然我們在被引入頁面中也不一定非得使用fragment ,在引用的時候 "::"是一個選擇器。可以爲footer的div起一個id = “footer”, 在引用的時候使用 ~{layout/footer::#footer}這樣也能引入。如果不加選擇器,則引用的就是整個頁面,例如像下面這種引用方式

<div th:replace="layout/footer"></div>

這樣就會把整個footer.html頁面的內容引用進來

其他佈局元素 replace,insert,include

  • replace :替換元素內容 2.0版本和3.0版本均支持
  • **insert **,3.0版本新增的標籤,會把需要的內容插入到父元素的內部
  • include ,3.0版本已經推薦放棄使用 上述說的比較抽象,具體看生成的代碼便一目瞭然
<div th:replace="layout/footer::copy"></div>
<div th:insert="~{layout/footer:: copy}"></div>
<div th:include="layout/footer::copy"></div>

生成後的代碼

<!--replace 在此處,替換div元素-->
<div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div>
<!--insert 在此處 footer中copy元素的內容會被插入到 div中-->
<div><div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div></div>
<!--include,footer中的內容會被插入到div中-->
<div>
    &copy; 2011 The Good Thymes Virtual Grocery
</div>

仔細觀察生成後的代碼,對這塊thymeleaf這塊的使用就會比較清晰了。這樣該使用哪個,就會變得比較自如。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章