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

本小妞迷上赌 提交于 2019-12-20 01:52:29

问题


I have a list called 'notifications' and I use Thymeleaf 'each method' to access its elements one by one. I can do this successfully as below.

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

note: 'message' is the attribute I need to retrieve from the list.

How can I access the elements in the reverse order? For an example if this is my current output,

Cat
Dog
Rat

How can I get output as this?

Rat
Dog
Cat

回答1:


I would reverse it server side, if possible. If you don't want to do that, maybe something like this would work for you:

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



回答2:


If you already use 'th:each' I want to complement the Metroids answer. It may be useful to declare a local variable. Thus, the inner part of the loop will not require changes.

<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>


来源:https://stackoverflow.com/questions/46443563/thymeleaf-how-to-loop-through-a-list-in-inverse-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!