web-dev-qa-db-fra.com

Comment faire si-sinon dans Thymeleaf?

Quelle est la meilleure façon de faire un simple if-else dans Thymeleaf?

Je veux obtenir dans Thymeleaf le même effet que

<c:choose>
  <c:when test="${potentially_complex_expression}">
     <h2>Hello!</h2>
  </c:when>
  <c:otherwise>
     <span class="xxx">Something else</span>
  </c:otherwise>
</c:choose>

dans JSTL.

Ce que j'ai compris jusqu'ici:

<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
    <h2 th:if="${condition}">Hello!</h2>
    <span th:unless="${condition}" class="xxx">Something else</span>
</div>

Je ne veux pas évaluer potentially_complex_expression deux fois. C'est pourquoi j'ai introduit la variable locale condition.

Pourtant, je n'aime pas utiliser à la fois th:if="${condition} et th:unless="${condition}".

La chose importante est que j'utilise 2 balises HTML différentes: disons h2 et span.

Pouvez-vous suggérer un meilleur moyen d'y parvenir?

96
Maciej Ziarko

Thymeleaf a un équivalent à <c:choose> et <c:when>: les attributs th:switch et th:case introduits dans Thymeleaf 2.0.

Ils fonctionnent comme prévu, en utilisant * pour le cas par défaut:

<div th:switch="${user.role}"> 
  <p th:case="'admin'">User is an administrator</p>
  <p th:case="#{roles.manager}">User is a manager</p>
  <p th:case="*">User is some other thing</p> 
</div>

Voir http://www.thymeleaf.org/whatsnew20.html#swit pour une explication rapide de la syntaxe (ou des tutoriels sur thymeleaf).

Clause de non-responsabilité, comme l'exigent les règles de StackOverflow: je suis l'auteur de thymeleaf.

170
Daniel Fernández

J'ai essayé ce code pour savoir si un client est connecté ou anonyme. J'ai utilisé les expressions conditionnelles th:if et th:unless. Un moyen assez simple de le faire.

<!-- IF CUSTOMER IS ANONYMOUS -->
<div th:if="${customer.anonymous}">
   <div>Welcome, Guest</div>
</div>
<!-- ELSE -->
<div th:unless="${customer.anonymous}">
   <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>
</div>
64
Lucky

J'aimerais partager mon exemple lié à la sécurité avec Daniel Fernández.

<div th:switch="${#authentication}? ${#authorization.expression('isAuthenticated()')} : ${false}">
    <span th:case="${false}">User is not logged in</span>
    <span th:case="${true}">Logged in user</span>
    <span th:case="*">Should never happen, but who knows...</span>
</div>

Voici une expression complexe avec des objets utilitaires mélangés 'authentification' et 'autorisation' qui produit un résultat 'vrai/faux' pour le code de modèle thymeleaf.

Les objets utilitaires 'authentification' et 'autorisation' proviennent de thymeleaf extras de la bibliothèque springsecurity3 . Lorsque l'objet 'authentication' n'est pas disponible OR autorisation.expression ('isAuthenticated ()') est évalué à ' false ', l'expression renvoie $ {false}, sinon $ {true}.

19
blandger

Vous pouvez utiliser 

If-then-else:  (if) ? (then) : (else)

Exemple:

'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))

Cela pourrait être utile pour les nouvelles personnes qui posent la même question.

16
Jad B.

Dans un cas plus simple (lorsque les balises HTML sont identiques):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>
8
GKislin

Une autre solution - vous pouvez utiliser la variable locale:

<div th:with="expr_result = ${potentially_complex_expression}">
    <div th:if="${expr_result}">
        <h2>Hello!</h2>
    </div>
    <div th:unless="${expr_result}">
        <span class="xxx">Something else</span>
    </div>
</div>

Plus sur les variables locales:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#local-variables

7
jareks

Une autre solution consiste simplement à utiliser not pour obtenir la négation opposée:

<h2 th:if="${potentially_complex_expression}">Hello!</h2>
<span class="xxx" th:if="${not potentially_complex_expression}">Something else</span>

Comme expliqué dans la documentation , c'est la même chose que d'utiliser th:unless. Comme d'autres réponses l'ont expliqué:

De plus, th:if a un attribut inverse, th:unless, que nous pourrions avoir utilisé dans l'exemple précédent au lieu d'utiliser un non-OGNL expression

Utiliser not fonctionne également, mais à mon humble avis, il est plus lisible d’utiliser th:unless au lieu d’annuler la condition avec not.

5
Pau
<div th:switch="${user.role}"> 
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
<p th:case="*">User is some other thing</p> 
</div>


<div th:with="condition=${potentially_complex_expression}" th:remove="tag">
<h2 th:if="${condition}">Hello!</h2>
<span th:unless="${condition}" class="xxx">Something else</span>
</div>
2
Vicky
<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

entrez la description de l'image ici

1
Tứ Nguyễn Duy