2016-12-16 153 views
3

我错过了大约30分钟试图找出如何从我的电子邮件服务生成HTML正文。这是一个计划任务,不是API调用 - 意味着没有控制器或MVC应用程序逻辑。只需处理模板。使用Thymeleaf处理电子邮件html

我有原始的java,我想用Thymeleaf处理单个* .html文件。怎么做?

换句话说,我需要Thymeleaf类比速度例如:

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

貌似我这里https://github.com/thymeleaf/thymeleaf/得到答案问题/ 561 –

回答

2

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