Search code examples
thymeleaf

Last Element in List in Thymeleaf


I have a list in Thymeleaf and I want to use th:with in a div to grab the last element in a list. I've tried:

<div th:if="${not #lists.isEmpty(licence.registrations)}" 
            th:with="lastRegistation=${licence.registrations[__(#lists.size(licence.registrations) - 1)__]}">
    <tr>
        <td>Name</td>
        <td><span th:text="${lastRegistration.name}"/></td>
    </tr>
</div>

However this gives me the error:

org.thymeleaf.exceptions.TemplateProcessingException: Could not parse as expression: "(#lists.size(licence.registrations) - 1)" (template: "admin/viewLicence.html" - line 103, col 10)

Does anyone know a way I can get the last item in a list with Thymeleaf?

Cheers,

Neil


Solution

  • If you're using preprocessing, you need to surround the expression with ${...}. Like this:

        th:with="lastRegistration=${licence.registrations[__${#lists.size(licence.registrations) - 1}__]}"
    

    That being said, there is no reason to use preprocessing in this case. (And I would remove the extra unused tags as well.) This will work:

    <tr th:if="${not #lists.isEmpty(licence.registrations)}"
        th:with="lastRegistration=${licence.registrations[#lists.size(licence.registrations) - 1]}">
        <td>Name</td>
        <td th:text="${lastRegistration.name}" />
    </tr>
    

    You can also get fancy with collection selection & projection, but I'm not sure this is an appropriate use. Still, it seems to work:

    <tr th:if="${not #lists.isEmpty(licence.registrations)}">
        <td>Name</td>
        <td th:text="${licence.registrations.![name].$[true]}" />
    </tr>