Answer the question
In order to leave comments, you need to log in
How to properly chain template resolvers in thymeleaf?
I'm setting up email templates. faced such a problem.
I declare a bin.
@Bean
public TemplateResolver mailTemplateResolver() {
TemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix(MAIL);
templateResolver.setSuffix(".html");
templateResolver.setOrder(1);
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCacheable(false);
return templateResolver;
}
@Bean
public TemplateResolver webTemplateResolver() {
TemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix(VIEWS);
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setOrder(2);
templateResolver.setTemplateMode("HTML5");
templateResolver.setCacheable(false);
return templateResolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(mailTemplateResolver());
templateEngine.addTemplateResolver(webTemplateResolver());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
@Bean
public AjaxThymeleafViewResolver viewResolver() {
AjaxThymeleafViewResolver thymeleafViewResolver = new AjaxThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine());
thymeleafViewResolver.setViewClass(FlowAjaxThymeleafView.class);
thymeleafViewResolver.setCharacterEncoding("UTF-8");
thymeleafViewResolver.setContentType("text/html; charset=UTF-8");
return thymeleafViewResolver;
}
final Context ctx = new Context(LocaleContextHolder.getLocale());
ctx.setVariable("name", "name");
ctx.setVariable("subscriptionDate", LocalDate.now());
ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
final String htmlContent = templateEngine.process("welcomeEmail", ctx);
org.thymeleaf.exceptions.TemplateProcessingException: Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]
Answer the question
In order to leave comments, you need to log in
You need to put the letter template files in the src/main/resources/mail folder and the bin configuration looks like this
@Bean
public ClassLoaderTemplateResolver emailTemplateResolver() {
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("mail/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setCacheable(false);
resolver.setCharacterEncoding("UTF-8");
resolver.setOrder(1);
return resolver;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question