【问题标题】:Using Thymeleaf to process email html使用 Thymeleaf 处理电子邮件 html
【发布时间】:2017-05-02 11:33:34
【问题描述】:

我错过了大约 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 );

附:我已阅读 this 问题,它没有提供答案。 Thymeleaf doc 和 thymeleafexamples-gtvg 都绑定到控制器逻辑、解析器和其他我不需要的东西。

【问题讨论】:

标签: java thymeleaf template-engine


【解决方案1】:

在 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2019-04-17
    • 2012-08-18
    • 2011-11-12
    • 2015-05-20
    • 2015-12-27
    相关资源
    最近更新 更多