Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Thymeleaf when the value is null

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?

like image 904
serkan Avatar asked Dec 17 '13 14:12

serkan


People also ask

How do you check null value in Thymeleaf?

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 .

How do you check condition in Thymeleaf?

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.

What is #{} in Thymeleaf?

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.


2 Answers

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> 
like image 75
Orest Avatar answered Oct 02 '22 13:10

Orest


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> 
like image 29
tduchateau Avatar answered Oct 02 '22 11:10

tduchateau