Search code examples
springthymeleafspring-el

Ternary operator returns 0 instead of character string


I am in the middle of rewriting my Spring MVC application from JSP pages to Thymeleaf templates. I am however experiencing the following problem.

When I am using ternary operator with results that are of different types namely java.lang.String and java.lang.Integer the string is always presented as 0 if the condition in ternary operator is not fulfilled.

<p th:text="#{free_transfers} + ': ' + (${i ne T(java.lang.Integer).MAX_VALUE}
? ${i} : '∞')">Cumulated free transfers: ∞</p>

The resulting HTML is however

<p>Free transfers: 0</p>

if i is equal Integer.MAX_VALUE.

At first I thought that this is because of the fact that the second argument is of type int so I explicitly added the conversion to character string.

<p th:text="#{free_transfers} + ': ' + (${i ne T(java.lang.Integer).MAX_VALUE}
? ${#strings.toString(i)} : '∞')">Cumulated free transfers: ∞</p>

however this does change anything and the result is still

<p>Free transfers: 0</p>

Does anybody have any idea how to achieve the expected result

<p>Free transfers: ∞</p>

?

I have also tried these ones but without any success.

|#{free_transfers}: ${i ne T(Integer).MAX_VALUE ? #strings.toString(i) : "∞"}|

|#{free_transfers}: ${i ne T(Integer).MAX_VALUE ? i : "∞"}|

Solution

  • It should be all within one ${} expression also you might not need toString just use i

      ${i ne T(java.lang.Integer).MAX_VALUE ? i : '∞'}