Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring + Thymeleaf show last two elements from list

I'm using MVC and send from Controller to Model a List of elements.

How can I wrote only last 2 elements from the List ?

Like this I print ALL elements from the List...

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

For example I have 10 News in list, like:

   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

What I should do in .html file using Thymeleaf to achieve the "hotest" news ? Like in example below:

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

I need only 2 elements. It's possible ?

like image 750
CeZet Avatar asked Nov 27 '15 00:11

CeZet


1 Answers

You can use the Iteration Status along with a th:if.

Once you define the iteration status variable in the th:each, you can access index and size which will give you the current position, and total length of the list. The th:if can then be used to only include the last 2 elements:

<li th:each="newsObject, iterStat : ${news}" th:if="${iterStat.index >= iterStat.size-2}">
    ... contents go here ...
</li>
like image 67
Andrew Avatar answered Nov 07 '22 00:11

Andrew