Using Thymeleaf when the value is null

2019-01-21 12:49发布

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?

8条回答
Emotional °昔
2楼-- · 2019-01-21 12:55

You can use 'th:if' together with 'th:text'

<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-21 12:58

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.

查看更多
Fickle 薄情
4楼-- · 2019-01-21 12:58

You've done twice the checking when you create

${someObject.someProperty != null} ? ${someObject.someProperty}

You should do it clean and simple as below.

<td th:text="${someObject.someProperty} ? ${someObject.someProperty} : 'null value!'"></td>
查看更多
5楼-- · 2019-01-21 13:06

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>
查看更多
爷、活的狠高调
6楼-- · 2019-01-21 13:13

This can also be handled using the elvis operator ?: which will add a default value when the field is null:

<span th:text="${object.property} ?: 'default value'"></span>
查看更多
Lonely孤独者°
7楼-- · 2019-01-21 13:13

Also worth to look at documentation for #objects build-in helper: https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#objects

There is useful: ${#objects.nullSafe(obj, default)}

查看更多
登录 后发表回答