举个栗子用上面三种方式引用下面这段:
<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>