Spring + Thymeleaf 显示列表中的最后两个元素

Spring + Thymeleaf show last two elements from list

我正在使用 MVC 并从控制器向模型发送一个元素列表。

如何只写入列表中的最后 2 个元素?

像这样打印列表中的所有元素...

<h2>NEWS</h2>
<ul>
  <li th:each="newsObject : ${news}">
    <small class="date"> <div th:text="${newsObject.getDate()}"/></small>
    <p th:text="${newsObject.getMessage()}"/>
  </li>
</ul>

例如我在列表中有 10 个新闻,例如:

   id|  date    | message
    1 2000-10-12 Something
    2 1999-11-12 Other message
    .
    .
    .
    9 2015-11-26 Oldest
    10 2015-11-27 The hotest

我应该在 .html 文件中使用 Thymeleaf 做什么来实现 "hotest" 消息? 就像下面的例子:

 2015-11-27 The hotest
 2015-11-26 Oldest

我只需要 2 个元素。有可能吗?

您可以将 Iteration Statusth:if 一起使用。

th:each 中定义迭代状态变量后,您可以访问 indexsize,这将为您提供当前位置和列表的总长度。然后 th:if 可用于仅包含最后 2 个元素:

<li th:each="newsObject, iterStat : ${news}" th:if="${iterStat.index >= iterStat.size-2}">
    ... contents go here ...
</li>