thymeleaf中的模板布局


一.包括模板片段:

  1:定義和引用片段,我們經常會想要包含在模板片段來自其他模板。常見的用途是頁腳、標題、菜單…;

為了做到這一點,Thymeleaf需要我們定義包含可用的片段,我們可以通過使用th:fragment屬性。

  定義一個頁面底部footer頁面,在每一個需要的頁面都可以用的模板,可以通過使用th:fragment屬性

  
    <div th:fragment="copy">
      &copy; 2014 The Good Thymes Virtual Grocery
    </div>

上面的代碼定義了一個叫做副本的片段,我們可以很容易地包含在我們的主頁上通過使用th:include or th:replace屬性之一:

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

引用片段沒有th:fragment:

...
<div id="copy-section">
  &copy; 2011 The Good Thymes Virtual Grocery
</div>
...

頁面引用:th:include="templatename::domselector"

templatename是要引入頁面的路勁加上去掉后綴的名稱,例如footer.html頁面建立在/WEB-INF/templates/footer.html,所以templatename為footer;domselector就是dom選擇器,即為th:fragment中的值,或是選擇id
<body>
  ...
  <div th:include="footer :: #copy-section"></div>
  
</body

注意:

帶有公共的頁面,不要帶有
<html>
    <head></head>
    <body></body>
</html>
直接寫內容:
    <div th:fragment="copy">
      © 2011 The Good Thymes Virtual Grocery
    </div>
  

  擴展寫法,希望能靈活運用:

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

二.可參數化的片段簽名

 可以像參數一樣傳入參數:

<div th:fragment="frag (onevar,twovar)">
    <p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>

兩種調用方式引入頁面:

<div th:include="::frag (${value1},${value2})">...</div>
<div th:include="::frag (onevar=${value1},twovar=${value2})">...</div>

如果沒有帶參數,如下形式:

<div th:fragment="frag">
    ...
</div>

依然可以使用帶參數的引入,但是必須使用第二種引入方式,另一種不行:如下是正確的引入方式

<div th:include="::frag (onevar=${value1},twovar=${value2})">

這樣事實上,這將是相當於一個th:includeth:with的組合

<div th:include="::frag" th:with="onevar=${value1},twovar=${value2}">

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM