Can I manually create Thymeleaf templates from String?

I have an upcoming project that has the following requirements:

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

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

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

I am open to suggestions on the best technology for work, but these are my preferences.

+4
source share
3 answers

Have you tried UrlTemplateResolver? Perhaps you can open the templates via the REST interface so that you can access the raw template using the URL. I have never tried this, but it seems possible. Otherwise, you will most likely need to implement your own template converter. Thymeleaf comes with servlets, files, URLs, and template developers. You basically need to write one for MongoDB.

See http://www.thymeleaf.org/apidocs/thymeleaf/2.0.17/org/thymeleaf/templateresolver/package-summary.html

+1
source

You can do it like this 1. Add a dependency:

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

OR, if you are not using spring boot, you can just add the thimeleaf 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.TemplateResolver; @Configuration public class TemplateEngineConfig { @Bean public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.addTemplateResolver(templateResolver()); return templateEngine; } private TemplateResolver templateResolver() { TemplateResolver resolver = new ClassLoaderTemplateResolver(); resolver.setPrefix("templates/mail/"); resolver.setSuffix(".html"); resolver.setTemplateMode("HTML5"); resolver.setOrder(1); resolver.setCacheable(true); return resolver; } } 
  1. display template.

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

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

+1
source

Thymeleaf is the "Java template engine for XML, XHTML, and HTML5." as defined on Wikipedia , problems can occur with strings.

So, you can compress the templates and save the tar in the BLOB database.

I found the OpenSource XML database is certainly useful for your project.

0
source

Source: https://habr.com/ru/post/1485982/


All Articles