Thymeleaf:如何以相反的顺序遍历列表?

Thymeleaf: How to loop through a list in inverse order?

我有一个名为 'notifications' 的列表,我使用 Thymeleaf 'each method' 一个一个地访问它的元素。我可以成功地做到这一点如下。

<li th:each="n : *{notifications}"> 
    <h4 type="text" th:text="*{n.message}"></h4>
</li>

注意:'message' 是我需要从列表中检索的属性。

如何以相反的顺序访问元素?例如,如果这是我当前的输出,

Cat
Dog
Rat

如何获得这样的输出?

Rat
Dog
Cat

如果可能的话,我会在服务器端反转它。如果您不想这样做,也许这样的方法对您有用:

<li th:each="i : ${#numbers.sequence(notifications.size() - 1, 0, -1)}"> 
    <h4 type="text" th:text="${notifications[i].message}"></h4>
</li>

如果您已经在使用 'th:each',我想补充 银河战士 的答案。声明一个局部变量可能很有用。因此,循环的内部不需要更改。

<li th:each="i : ${#numbers.sequence(notifications.size() - 1, 0, -1)}"
     th:with="n=${notifications[i]}"> 
    <h4 type="text" th:text="${n.message}"></h4>
</li>