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)