我错过了大约 30 分钟的时间来弄清楚如何从我的电子邮件服务生成 HTML 正文。这是计划任务,而不是 API 调用 - 意味着没有 Controller 或 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 );
附言我读过 this问题,它没有提供答案。 Thymeleaf 文档和 thymeleafexamples-gtvg绑定(bind)到 Controller 逻辑、解析器和其他我不需要的东西。
最佳答案
在 thymeleaf 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);
关于java - 使用 Thymeleaf 处理电子邮件 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41188315/