Search code examples
javaspringthymeleaftemplate-engine

SpringTemplateEngine.process doesn't read file (thymeleaf)


I'm trying to use a Thymeleaf template engine to create an html email, by following this tutorial.

I've created the template configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.nio.charset.StandardCharsets;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;


@Configuration
public class ThymeleafTemplateConfiguration {
  @Bean
  public SpringTemplateEngine springTemplateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.addTemplateResolver(htmlTemplateResolver());
    return templateEngine;
  }

  @Bean
  public SpringResourceTemplateResolver htmlTemplateResolver(){
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setPrefix("/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
    return templateResolver;
  }
}

and an html template:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <p>This is the body to be changed</p>
  <p>This is a name: ${name}</p>
</body>
</html>

Then I try to populate the template:

templateEngine = new SpringTemplateEngine();
Context context = new Context();
context.setVariable("name", "my name");

String html = templateEngine.process("index", context);
System.out.println(html);

But rather than getting the populated template, I'm just getting the first parameter I put into process:

>>> my name

What am I doing wrong? why does process take the parameter as-is rather than reading the file with the specified prefix and suffix? (/templates/index.html)


Solution

  • Note that in the example you mention a bean called SpringTemplateEngine is being created and the SpringResourceTemplateResolver is being injected into it.

    Your code does not make any use of the created bean. Instead it creates an new instance of SpringTemplateEngine. My guess, this new instance does not know SpringResourceTemplateResolver.

    Two possible fixes

    1. Autowired the bean instead of creating new instance
    2. Create this instance the same way you create the bean, i.e addTemplateResolver to the new instance