Thymeleaf 模板佈局和屬性優先順序
Thymeleaf 模板佈局和屬性優先順序
th:insert,th:replace,th:include三者的區別
- th:insert 它將簡單地插入指定的片段作為正文的標籤
- th:replace 用指定實際片段來替換其主標籤
- th:include 類似於th:insert ,但不是插入片段它只插入此片段的內容(3.x版本後,不再推薦使用)
舉個栗子用上面三種方式引用下面這段:
<footer th:fragment="copy"> © 2019 https://blog.eunji.cn"愛敲程式碼的貓" </footer>
引用:
<body> ... <div th:insert="footer :: copy"></div> <div th:replace="footer :: copy"></div> <div th:include="footer :: copy"></div> </body>
最終會是下面這種效果:
<body> ... <div> <footer> © 2019 https://blog.eunji.cn"愛敲程式碼的貓" </footer> </div> <footer> © 2019 https://blog.eunji.cn"愛敲程式碼的貓" </footer> <div> © 2019 https://blog.eunji.cn"愛敲程式碼的貓" </div> </body>
屬性優先順序
th:* 在同一個標籤中寫入多個屬性會發生什麼?例如:
<ul> <li th:each="item : ${items}" th:text="${item.description}">Item description here..</li> </ul>
我們希望該th:each 屬性在之前執行,th:text 以便我們得到我們想要的結果,但是考慮到 HTML / XML 標準沒有給標記中的屬性寫入的順序賦予任何意義,優先順序 必須在屬性本身中建立機制,以確保它將按預期工作。
因此,所有 Thymeleaf 屬性都定義了一個數字優先順序,它確定了它們在標記中執行的順序。這個順序是:
順序 | 功能 | 屬性 |
---|---|---|
1 | 片段包含 | th:insert th:replace |
2 | 片段的迭代 | th:each |
3 | 條件判斷 | th:if th:unless **th:switch **th:case |
4 | 區域性變數的定義 | th:object th:with |
5 | 通用屬性修改 | th:attr th:attrprepend th:attrappend |
6 | 特定屬性修改 | th:value th:href th:src ... |
7 | 文字(標籤主體修改) | th:text th:utext |
8 | 片段規範 | th:fragment |
9 | 片段刪除 | th:remove |
這個優先順序機制意味著如果屬性位置被反轉,上面的迭代片段將給出完全相同的結果(雖然它的可讀性稍差):
<ul> <li th:text="${item.description}" th:each="item : ${items}">Item description here..</li> </ul>
本文由Aquan 創作,採用知識共享署名4.0 國際許可協議進行許可
本站文章除註明轉載/出處外,均為本站原創或翻譯,轉載前請務必署名
最後編輯時間為: 三月 8,2019