Thymeleaf - Best practice for checking for NULL when formatting (ie. dates)

user1812806 picture user1812806 · Dec 11, 2012 · Viewed 20.9k times · Source

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)

Answer

Daniel Fernández picture Daniel Fernández · Dec 13, 2012

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)