Search code examples
javathymeleaf

Thymeleaf - conditional rendering based on value of object property


<tr th:each="student: ${students}">
    <td th:text="${student.id}" />
    <td th:text="${student.name}" />
</tr>

I have 10 students with different names. I only want to render the whole table if there is AT LEAST 1 student with student.name == "Felix". Otherwise I don´t want to render the table.

How can I do that?


Solution

  • In the controller which returns this template, check the list in Java. If you find "Felix".equals(student.name) then add a variable like 'isRenderTable' to the context and do a conditional on the table in Thymeleaf, like:

    <table th:if="${isRenderTable}">...</table>
    

    If you don't want to touch the server side code, then you can use Thymeleaf and JavaScript. Render the student list into JS, then use JS to perform the logical comparison you want, then render the table via JS.

    Another way to do it is to render the student list into JS, and also render the table in Thymeleaf (and keeping the table hidden with CSS), then in JS if you detect the proper condition, change the CSS to show the table.