I have an upcoming project which has the following requirements:
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.
You can do it like this:
<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.
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;
}
}
src/main/resources/templates/mail/myfile.html
:
<html>
<body>
<div th:text="${myDivContent}"></div>
</body>
</html>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With