【问题标题】:Spring + Thymeleaf show last two elements from listSpring + Thymeleaf 显示列表中的最后两个元素
【发布时间】:2016-03-01 03:25:01
【问题描述】:

我正在使用 MVC 并从 Controller 向 Model 发送元素列表。

我怎样才能只写 List 中的最后 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 来实现“最热门”新闻? 如下例所示:

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

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

【问题讨论】:

    标签: java spring spring-mvc thymeleaf


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2021-07-12
      • 2020-10-13
      相关资源
      最近更新 更多