Search code examples
springspring-bootthymeleaf

Pagination with Spring Boot and Thymeleaf


I am looking for a CLEAN example that explains how pagination is done using thymeleaf and spring boot.

There are a lot of examples out there, but they are not complete.

I am actually looking for an example that implements pagination blocks as well. For example, if the total pages is 150, I would like the pages to show in blocks as in << 1 - 2 - 3 - 4 - 5... >>, when you click the arrows, the next block of pages would show as << 6 - 7 - 8 - 9 - 10... >>

Thank you


Solution

  • I found a simple solution using Java math methods: Math.max and Math.min as follows:

        int current = page.getNumber() + 3;
        int begin = Math.max(1, current - 5);
        int end = Math.min(begin + 6, page.getTotalPages());
    

    I then passed these variables to thymeleaf #numbers.sequence as in:

                    <li class="page-item"
                    th:each="i : ${#numbers.sequence(beginIndex, endIndex)} ">
    
                    <a th:href="@{/jobs(p=${i})}" th:text="${i}" class="nav-link"
                    th:classappend="${currentPage}==${i}?'activepagenumber':''"></a>
                    </li>