Search code examples
htmlspring-bootthymeleaf

How to render different result in single <td> tag depending on double value in thymeleaf


I have a table where I want to render different values in a <td> HTML tag according to my prod.price. For example when the prod.price < 1 I want to show 0.30 c. When prod.price > 1 Thymeleaf should render 1.20 aws.

My current implementation, unfortunately, shows both aws and c when the prod.price < 1. For example if the price is 0.30c my solution will render both 0.30c and 0.30aws. I am not sure what is wrong and why it gives me this result and some help figuring out this would be appreciated. The implementation I have now looks like this -

<td th:text="${prod.name}"></td>
            <td>
                <span th:if="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} &lt; 1">
                <span th:text="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} + ' clouds'"></span>
            </span> 
                <span th:unless="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} &gt; 1"></span>
                <span th:text="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} + ' aws'"></span>

            </td>

I also played a lot with the <span> tags, but I did not achieve much success. My initial approach, in the beginning, is below but is also not working.

            <td>
            <span th:if="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} &lt; 1" th:text="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} + ' clouds'"></span>
            <span th:unless="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} &gt; 1" th:text="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} + ' aws'"></span>

            </td>

Solution

  • You wereclose. This should work:

    <td>
        <span th:if="$prod.price} &lt; 1" 
              th:text="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} + ' clouds'">
        </span>
        <span th:if="${prod.price} &gt; 1" 
              th:text="${#numbers.formatDecimal(prod.price, 1, 'COMMA', 2, 'POINT')} + ' aws'">
        </span>
    </td>