我错过了大约30分钟试图弄清楚如何从我的电子邮件服务生成HTML正文。这是一个计划任务,而不是API调用 - 意味着没有控制器或MVC应用程序逻辑。只需处理模板。
我有原始java,我想用Thymeleaf处理单个* .html文件。怎么做?
换句话说,我需要Thymeleaf类比Velocity例子:
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。我已阅读this问题,但未提供答案。 Thymeleaf doc和thymeleafexamples-gtvg都绑定了控制器逻辑,解析器和其他我不需要的东西。
答案 0 :(得分:2)
在百里香叶3中,解决方案非常相似:
/**
* 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;
}
最后是代码:
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);