10 属性优先级

当你在同一个标签里,写上多个th:*属性时,会发生什么🤔呢? 比如:

  1. <ul>
  2. <li th:each="item : ${items}" th:text="${item.description}">Item description here...</li>
  3. </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

这种优先级机制意味着:如果颠倒属性的位置(尽管可读性会稍微变差),上面的片段遍历也会得到完全相同的结果:

  1. <ul>
  2. <li th:text="${item.description}" th:each="item : ${items}">Item description here...</li>
  3. </ul>