How to print different text based on a variable value in thymeleaf?

xpz :
<p th:text="|Commande no : ${expedition.idCommande}|" class="font-weight-bold"></p>

<p th:text="${expedition.etat}"></p>

expedition.etat is an int which takes value either 0, 1, or 2

I`d like to have the second paragraph to have inner text "In preparation", "Sent", or "Delivered", instead of 0, 1, 2.

I suppose i could put 3 paragraphs with each a th:if and th:text to solve the problem; Or maybe I could add a getStatusAsText method in my expedition object; but isn't there a better way to implement this ?

vphilipnyc :

You can simply switch on the value:

<div th:switch="${expedition.etat}">
    <p th:case="0">In preparation</p>
    <p th:case="1">Sent</p>
    <p th:case="2">Delivered</p>
    <p th:case="*">No state found</p>
</div>

You can use <th:block> if you don't want to print HTML tags. You can consider making the default case red or your preferred error color. Do make sure that the default case is last.

You'll want to print these values from a message bundle if you need the text to appear in multiple languages, but that is outside the scope of this question.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=370585&siteId=1