Thymeleaf: sprawdź czy zmienna jest zdefiniowana

Jak sprawdzić czy zmienna jest zdefiniowana w Thymeleaf?

Coś takiego w Javascript:

if (typeof variable !== 'undefined') { }

Lub to w PHP:

if (isset($var)) { }

Czy istnieje odpowiednik w Tymeleaf?

Author: Andrea, 2015-02-28

4 answers

Tak, możesz łatwo sprawdzić, czy dana właściwość istnieje dla Twojego dokumentu za pomocą następującego kodu. Zauważ, że tworzysz tag div jeśli warunek jest spełniony:

<div th:if="${variable != null}" th:text="Yes, variable exists!">
   I wonder, if variable exists...
</div>

Jeśli chcesz użyć pola variable, warto sprawdzić, czy to pole również istnieje

<div th:if="${variable != null && variable.name != null}" th:text="${variable.name}">
   I wonder, if variable.name exists...
</div>

Lub nawet krótszy, bez użycia instrukcji if

<div th:text="${variable?.name}">
   I wonder, if variable.name exists...
</div>`

Ale używając tej instrukcji zakończysz tworzenie znacznika div Czy variable Czy variable.name exist

Możesz dowiedzieć się więcej o uwarunkowaniach w tymeleaf tutaj

 69
Author: Trynkiewicz Mariusz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-06 04:25:34

Krótka forma:

<div th:if="${currentUser}">
    <h3>Name:</h3><h3 th:text="${currentUser.id}"></h3>
    <h3>Name:</h3><h3 th:text="${currentUser.username}"></h3>
</div>
 12
Author: Lay Leangsros,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-18 16:49:57

Aby stwierdzić, czy kontekst zawiera daną zmienną, można bezpośrednio zapytać mapę zmiennej kontekstowej. Pozwala to określić, czy zmienna jest w ogóle określona, w przeciwieństwie do tylko przypadków, w których jest zdefiniowana, ale z wartością null.

Tymeleaf 2

Użyj #vars obiekt containsKey "metoda": {]}

<div th:if="${#vars.containsKey('myVariable')}" th:text="Yes, $myVariable exists!"></div>

Tymeleaf 3

Użyj #ctx obiekt containsVariable "metoda": {]}

<div th:if="${#ctx.containsVariable('myVariable')}" th:text="Yes, $myVariable exists!"></div>
 8
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-04 12:44:13

Możesz używać operatorów warunkowych. To zapisze zmienną, jeśli istnieje lub pusty łańcuch:

<p th:text="${variable}?:''"></p>
 0
Author: Aleksandar Nikolic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-07 22:53:31