Search code examples
javathymeleaf

How to pre-evaluate statements in thymeleaf in concatenations?


if price is null, nothing is shown: th:text="${row?.price}

if price is null, actually 'null' is printed: th:text="${row?.price + ' ' + row?.currency}

How can I tell thymeleaf to evaluate the statements itself before printing them?


Solution

  • You can use th:if to conditionally show a HTML tag:

    <span th:if="${row?.price}" th:text="${row.price + ' ' + row.currency}"/>
    

    The th:if is evaluated before the th:text.

    If you want to hide the currency independent from the price, you can do this:

    <div>
      <span th:if="${row?.price}" th:text="${row.price}"/>
      <span th:if="${row?.currency}" th:text="${row.currency}"/>
    </div>
    

    For the space, add a &nbsp; between the span elements, or use CSS to style it like you want.