AnilkumarReddy
AnilkumarReddy

Reputation: 145

How to load the HTML templates from data base in spring thymeleaf 3.?

How to load my string content of the HTML template from DB in spring boot 2.0.0.RELEASE and THYMELEAF3.0.

Context context = new Context(); 
context.setVariable("comments", comments); 
templateEngine.process("singup-request-user-template", context);//HERE I NEED TO PASS THE DB LOADING CONTENT

Upvotes: 2

Views: 3813

Answers (1)

Ruslan Akhundov
Ruslan Akhundov

Reputation: 2216

If you can't use ThymeleafDatabaseResourceResolver the other option would be to fetch your template manually in java code, and then process it:

String databaseTemplate = ...fetch template from db...
Context context = new Context(Locale.ENGLISH);
...set variables for context....
String processedTemplate = templateEngine.process(databaseTemplate, context);

You should also manually create template engine:

SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(new SpringResourceTemplateResolver());
templateEngine.addTemplateResolver(new StringTemplateResolver());
templateEngine.addTemplateResolver(new FileTemplateResolver());

This would work if your database contains either path to the template file or template content itself. However if you are sure that your database always holds a path to file, then you can just autowire standard TemplateEnging configured by spring-boot.

Also you might want to take a look at ITemplateResolver interface and its implementations, in case your templates are located somewhere else.

Upvotes: 1

Related Questions