2016-12-16 98 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);