Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

thymeleaf

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) 
like image 711
user1812806 Avatar asked Dec 11 '12 17:12

user1812806


People also ask

How do you handle null in Thymeleaf?

Another way to handle null values in the Thymeleaf templates is by using the Elvis operator or default expression. It is a special kind of conditional expression without a then part. Elvis operator lets you specify two expressions in one attribute.

Why Thymeleaf is best suited to use in XHTML and html?

It is better suited for serving XHTML/HTML5 in web applications, but it can process any XML file, be it in web or in standalone applications. The main goal of Thymeleaf is to provide an elegant and well-formed way of creating templates.

What is th block Thymeleaf?

th:block is a Thymeleaf element rather than an attribute, and it has the general syntax: 1 2 3. <th:block> <!-- Your HTML code --> </th:block> th:block allows you to apply the same Thymeleaf attribute, like th:if or th:each to a block of code.


2 Answers

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)

like image 67
Daniel Fernández Avatar answered Sep 18 '22 00:09

Daniel Fernández


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.

like image 27
Julien May Avatar answered Sep 20 '22 00:09

Julien May