26

I have a Thymeleaf template code to format a date. There are times when that date will be null in the returned object. What is the best way to check for null in Thymeleaf in this situation? Currently the template is throwing the following error:

Caused by: java.lang.IllegalArgumentException: Cannot apply format on null
    at org.thymeleaf.util.Validate.notNull(Validate.java:37)
    at org.thymeleaf.util.DateUtils.format(DateUtils.java:182)
    at org.thymeleaf.expression.Dates.format(Dates.java:164)
Honza Zidek
  • 9,204
  • 4
  • 72
  • 118
user1812806
  • 275
  • 1
  • 3
  • 6

2 Answers2

58

You can also use a conditional expression on your object, so that the formatting method is only applied if you object is not null: th:text="${myDate} ? ${#dates.format(myDate,...)}"

Note there is no "else" part in the expression above, and in that case the expression will simply return null (making the th:text attribute write nothing).

(Disclaimer required by StackOverflow: I am the author of thymeleaf)

Daniel Fernández
  • 7,335
  • 2
  • 30
  • 33
  • 1
    Thanks for the response. I actually got this approach working but decided to validate the values on the server side to keep the templates more readable and "clean". Thanks for the response. – user1812806 Dec 21 '12 at 18:50
  • I think that this is actually a **bug** in Thymeleaf. The `dates.format` and `temporals.format` should simply return `null` in case that the input value is `null`. It is very annoying to add these boilerplate `if`s everywhere :( – Honza Zidek Jul 20 '17 at 08:56
  • I have similar issue, where as my data object is not null. it is giving me un -formatted date if I use this code "06/23/2013" but when I use 06/23/2013 it gives me null... any idea @Daniel Femandez – Ghost Rider Feb 07 '18 at 14:21
6

you can either use thymeleafs objects utility class Objects or validate the object before passing it to the template.

i prefer the prevalidation as you normally do not want to hack around in your template. also that way you keep your data loosely coupled from the view.

Julien May
  • 2,011
  • 15
  • 18
  • 1
    I went with this approach although I don't necessarily see handling a null value in the template a hack per se, but it does muck up the template and arguably breaks the separation of concerns for views and their data. – user1812806 Dec 21 '12 at 18:49