Search code examples
javathymeleaf

Thymeleaf - tag inside th:text


I need to put tag or text based on some expression. I tried an expression like this bud didn't work.

<td th:text="${reservation[0] == null ? <a href="/reserve">Reserve</a> : reservation[0] == request.username ? <a href="/cancel">Cancel</a> : Reserved}"></td>

Solution

  • Try this :

    <td th:utext="${reservation[0] == null} ? '<a href="/reserve">Reserve</a>' :  ${reservation[0] == request.username} ? '<a href="/cancel">Cancel</a>' : 'Reserved'"></td>
    

    You can also make it easier to read with multiple test conditions:

    <td th:if="${reservation[0] == null}"><a href="/reserve">Reserve</a></td>
    <td th:if="${reservation[0] == request.username}"><a href="/cancel">Cancel</a></td>
    

    If the condition is not fullfilled then th tag is not displayed.