Search code examples
spring-mvcpaginationspring-datathymeleaf

How to use Thymeleaf's #lists.isEmpty with Spring Data's Page interface?


I use jpenren's Thymeleaf Spring Data Dialect: https://github.com/jpenren/thymeleaf-spring-data-dialect

Following his last advice:

By default SpringDataDialect search in the request for the attribute "page" or if one attribute of type org.springframework.data.domain.Page exists. To use another model attribute, use sd:page-object="${attrName}"

I do something like this in my Spring controller:

@RequestMapping("search")
public String search(Model model, @PageableDefault Pageable pageable) {
    Page<User> users = userRepository.findAll(pageable);
    model.addAttribute("users", users);
    return "user/search";
}

and in my search.html view, here's an excerpt:

    <table class="table">
      <caption class="text-xs-center" th:if="${#lists.isEmpty(users)}">No user found</caption>
      <thead>
        <tr>
          <th>Username</th>

            (...)

      <tbody>
        <tr th:each="user : ${users}">
          <td th:text="${user.name}">Username</td>

Unfortunately the ${#lists.isEmpty(users)} doesn't work. It works on other pages where I do not make use of this Page<?>.

So how do I do this test?


Solution

  • It looks like Thymeleaf's #lists really expects a List which Page clearly is not as it only implements Iterable. You can refer to page.content for the lists content.

    As you're rather checking for the presence (or absence) of content in the first place, you could use Page.hasContent() directly, which means that a th:unless="{adherents.hasContent()} should do the trick as well.