I have some values in my database which can be null if they have not already been entered.
But when I use Thymeleaf in my html, it gives an error when parsing null values.
Is there any way to handle this?
The safe navigation operator can be used in Thymeleaf to check whether the reference to an object is null or not, before accessing its fields and methods. It will just return a null value instead of throwing a NullPointerException .
To achieve similar to if-else condition in Thymeleaf we can use th:switch attribute. Thymeleaf at the first step will evaluate ${condition} expression and if the value is true it will print p tag with TRUE text.
Variable expressions are OGNL expressions –or Spring EL if you're integrating Thymeleaf with Spring. *{} is used for selection expressions. Selection expressions are just like variable expressions, except they will be executed on a previously selected object. #{} is used for message (i18n) expressions.
The shortest way is using '?' operator. If you have User entity with embedded Address entity in order to access fields of Address entity and print them if address is not null, otherwise here will be an empty column:
<td th:text="${user?.address?.city}"></td>
Sure there is. You can for example use the conditional expressions. For example:
<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty} : 'null value!'">someValue</span>
You can even omit the "else" expression:
<span th:text="${someObject.someProperty != null} ? ${someObject.someProperty}">someValue</span>
You can also take a look at the Elvis operator to display default values like this:-
<span th:text="${someObject.someProperty} ?: 'default value'">someValue</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With