0

I'm struggling to format a LocalDate in Thymeleaf like so:

    <div th:object="${objectWithDateField}">
        <span th:text="*{#temporals.format(date)}"></span>
    </div>

This throws a NPE with the message: target is null for method format where target refers to the parameter of the format() method.

So my question is: What am I doing wrong or is this a bug in Thymeleaf?

When I'm not formatting the date and just render it like the following it shows the date correctly.

    <div th:object="${objectWithDateField}">
        <span th:text="*{date}"></span>
    </div>

I'm running this code in a unit test at the moment and added an assertion that confirms to me that the date is definitely not null before passing the object to the context (also confirmed by rendering without the call to format()).

I already tried the solutions from this thread and someone in the comments had the same problem I'm describing unfortunately without an answer.

I'm using the following versions:

  • Spring Boot Starter Thymeleaf: 2.7.2
  • ognl: 3.2.1 (I'm not using SpEL)

EDIT:

For clarification: I've registered my own TemplateEngine bean and annotated it with @Primary to be able to use Thymeleafs default dialect like so:

    @Bean
    @Primary
    public TemplateEngine myTemplateEngine() {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);

        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        return templateEngine;
    }

The thymeleaf-extras-java8time is present in the runtime classpath as it's pulled in transitively via spring-boot-starter-thymeleaf.

Malte Esch
  • 1
  • 1
  • 3
  • For clarification: Can you show how you have configured Thymeleaf? I don't know how you can use Spring Boot Starter Thymeleaf, but not be using SpEL - I am not familiar with that set-up. Also, just for clarification: You are using the `thymeleaf-extras-java8time` JAR? – andrewJames Dec 01 '22 at 19:55

1 Answers1

0

So I found the solution.

The target in the NPEs exception message was in fact not referring to the parameter of format (which is also named target). It is referring to the #temporals context object.

So to solve the problem I added the Java8TimeDialect from the above mentioned thymeleaf-extras-java8time library to my TemplateEngine bean like so:

templateEngine.addDialect(new Java8TimeDialect());

From here on everything worked as expected.

Malte Esch
  • 1
  • 1
  • 3