Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I render Thymeleaf templates manually from a String?

I have an upcoming project which has the following requirements:

  • Very simple to use (end-users will be expected to use it)
  • Java based, the project will be written in Spring3
  • String based loading (although open to similar suggestions) as I will be storing the templates in a database, not as files

The tricky part of this seems to be getting a templating engine to load the template from the database.

I quite like the look of Thymeleaf, but I have no idea how to render the template manually from a string - has anybody tried this?

I am open to suggestions for a better technology for the job, but this is my preference.

like image 605
theZenPebble Avatar asked Jun 13 '13 11:06

theZenPebble


1 Answers

You can do it like this:

1. Add dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

OR, if you are not use spring boot, you can just add thymeleaf dependency.

2. Config resolver

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.ITemplateResolver;

@Configuration
public class TemplateEngineConfig {
    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.addTemplateResolver(templateResolver());
        return templateEngine;
    }

    private ITemplateResolver templateResolver() {
        ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
        resolver.setPrefix("templates/mail/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode("HTML5");
        resolver.setOrder(1);
        resolver.setCacheable(true);
        return resolver;
    }
}

3. Create your template

src/main/resources/templates/mail/myfile.html:

<html>
    <body>
    <div th:text="${myDivContent}"></div>
    </body>
</html>

4. Render the template using org.thymeleaf.context.Context

    Context myContext = new Context();
    myContext.setVariable("myDivContent", "Hello, the weather is foggy");

    String htmlTemplate = templateEngine.process(templateName, myContext);

The templateName is a string variable. The templateContext is a org.thymeleaf.context.Context impl.

like image 151
BeeNoisy Avatar answered Sep 23 '22 02:09

BeeNoisy