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)

2 Answers 2

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)

3
  • 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. Dec 21, 2012 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 ifs everywhere :( Jul 20, 2017 at 8: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 "<td th:text="*{dateOfBirth}">06/23/2013</td>" but when I use <td th:text="${#temporals.format(*{dateOfBirth},'dd-mm-yyyy')}">06/23/2013</td> it gives me null... any idea @Daniel Femandez Feb 7, 2018 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.

1
  • 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. Dec 21, 2012 at 18:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.