2
<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 ?

xpz
  • 268
  • 2
  • 9
  • 1
    Different ways to handle this problem, and it's probably just best to use `if` statements - but does `expedition.etat` accept `expedition.idCommande` as the parameter? Is the value computed on the server-side or client-side? There are examples in the Thymeleaf docs. Look at using `th:with` for the parameter. – riddle_me_this Mar 29 '20 at 18:23
  • expedition is passed as a model attribute and corresponds to a plain java object with 3 fields : int id, int idCommande and int etat (french for status) ( private fields with regular getters and setters - i guess it is mandatory for use in thymeleaf, right ?). so there is no dependency btw etat and idCommande, they are 2 fields of same object that's it. And everything is done server-side i guess (unless i am very wrong about how thymeleaf works when used as templating framework inside spring mvc). – xpz Mar 29 '20 at 18:37
  • thks i will look into th:with – xpz Mar 29 '20 at 18:37
  • th:with doesnt look like what i need (i dont want to declare new variable). I am just looking for a thymeleaf way to have a switch and then for each value specify a different th:text attribute...... if such a thing exists in thymeleaf – xpz Mar 29 '20 at 18:41
  • Ok, but how do you compute whether it is 0, 1, or 2? Is that from another service? Or provided by the user on the client-side? – riddle_me_this Mar 29 '20 at 18:41
  • from another service, and not dependent on user. – xpz Mar 29 '20 at 18:43
  • Or sure - that's easy: https://stackoverflow.com/questions/29657648/thymleaf-switch-statement-with-multiple-case – riddle_me_this Mar 29 '20 at 18:44
  • Does this answer your question? [How to do if-else in Thymeleaf?](https://stackoverflow.com/questions/13494078/how-to-do-if-else-in-thymeleaf) – Eklavya Mar 29 '20 at 18:57

1 Answers1

2

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.

riddle_me_this
  • 8,575
  • 10
  • 55
  • 80