web-dev-qa-db-fra.com

Thymeleaf: affiche le texte si l'attribut et la propriété existent

Existe-t-il un moyen simple dans thymeleaf pour afficher le contenu d'une propriété d'attribut si la propriété et l'attribut existent? S'il y a un attribut "erreur" avec une propriété "résumé" dans ma page html, je voudrais le montrer:

<span th:text="${error.summary}">error summary</span>

S'il n'y a pas d'attribut "erreur", l'erreur suivante est générée:

org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Field or property 'summary' cannot be found on null

Actuellement, j'utilise l'approche suivante, qui semble tout simplement trop compliquée.

<span th:if="${error != null and error.summary != null}"><span th:text="${error.summary}">error summary</span></span>

Existe-t-il un moyen plus simple d'y parvenir?

21
James

Sûr! Puisque le processeur associé au th:if l'attribut a un priorité plus élevée que celui associé au th:text, il sera évalué en premier. Vous pouvez ainsi écrire:

<span th:if="${error != null && error.summary != null}" th:text="${error.summary}">Static summary</span>

Vous pouvez même le raccourcir en utilisant:

<span th:text="${error?.summary}">Static summary</span>

Mais je pense que dans ce cas, que le résumé existe ou non, la balise span sera créée, ce qui est un peu moche.

Voir plus d'informations sur les expressions conditionnelles ici .

48
tduchateau