Using Thymeleaf to process email html

1.2k Views Asked by At

I have missed about 30 minutes trying to figure out how to generate HTML body from my email service. This is a scheduled task, not an API call - means no controllers or MVC app logic. Just process template.

I have raw java and I want to process single *.html file with Thymeleaf. How to do that?

In other words, I need Thymeleaf analogy for Velocity example:

VelocityEngine ve = new VelocityEngine();
ve.init();
Template t = ve.getTemplate( "helloworld.vm" );
VelocityContext context = new VelocityContext();
context.put("name", "World");
StringWriter writer = new StringWriter();
t.merge( context, writer );

P.S. I've read this issue, it doesn't provide an answer. Both Thymeleaf doc and thymeleafexamples-gtvg are bound to controller logic, resolvers and other stuff I do not need.

1

There are 1 best solutions below

0
On

In thymeleaf 3 the solution is very similar:

  /**
   * THYMELEAF: Template Engine (Spring4-specific version) for HTML email
   * templates.
   */
  @Bean
  public ITemplateEngine htmlTemplateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    templateEngine.setTemplateResolver(htmlTemplateResolver());
    return templateEngine;
  }

  /**
   * THYMELEAF: Template Resolver for HTML email templates.
   */
  private ITemplateResolver htmlTemplateResolver() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(CLASS_LOADER);
    templateResolver.setPrefix("/emails/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setCharacterEncoding(ENCODING);
    templateResolver.setCacheable(false);
    return templateResolver;
  }

and finally the code:

private final Locale LOCALE = new Locale("pl", "PL");
final Context ctx = new Context(LOCALE);
ctx.setVariable("name", "World");

String html = htmlTemplateEngine.process("layouts/layout.html", ctx);