Process HTML file using Thymeleaf in Web based Scopes of Spring and store the processed template as String

后端 未结 5 1404
无人共我
无人共我 2021-01-02 14:21

I am trying to render an HTML file using thymeleaf and keep the resultant HTML content in a String variable in web-based scopes of Spring so that i can use it l

5条回答
  •  醉梦人生
    2021-01-02 14:56

    I'm using similar Springboot and Thymeleaf versions and something like this worked for me on a few projects :

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.thymeleaf.TemplateEngine;
    import org.thymeleaf.context.Context;
    
    @Component
    public class EmailProcessor {
    
        private TemplateEngine htmlTemplateEngine;
    
        @Autowired
        public EmailProcessor(TemplateEngine templateEngine) {
            this.htmlTemplateEngine = templateEngine;
        }
    
    
        public String process(User user) {
    
            final Context ctx = new Context();
    
            if (user != null) {
                ctx.setVariable("user", user);
            }
    
            return htmlTemplateEngine.process("emails/template", ctx);
        }
    }
    

    Email template is just a regular Thymeleaf template which is located in:

    resouces/templates/emails/template.html

提交回复
热议问题