Tuesday, March 7, 2017

Getting started with Thymeleaf 3 text templates

Text ((org.thymeleaf.templatemode.TemplateMode#TEXT)) templates in Thymeleaf allow creating templates with no markup. Such templates can be used to genere non-HTML content like e.g. source code, markdown files or text emails. See how easy it is to utilize text templates with Thymeleaf.

Configure template engine with template resolver

@Configuration
public static class ThymeleafConfig {

    @Bean(name = "textTemplateEngine")
    public TemplateEngine textTemplateEngine() {
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.addTemplateResolver(textTemplateResolver());
        return templateEngine;
    }

    private ITemplateResolver textTemplateResolver() {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setPrefix("/templates/text/");
        templateResolver.setSuffix(".txt");
        templateResolver.setTemplateMode(TemplateMode.TEXT);
        templateResolver.setCharacterEncoding("UTF8");
        templateResolver.setCheckExistence(true);
        templateResolver.setCacheable(false);
        return templateResolver;
    }
}

textTemplateResolver() method configures template resolver for text templates. In this example, templates will be read from classpath.

Create text template

Create /templates/text/text-template.txt file on your classpath (e.g. src/main/resources)

Name: [(${name})]
Link: [(${url})]
Tags:
[# th:each="tag : ${tags}" ]
    [(${tag})]
[/]

Process the template

TemplateEngine textTemplateEngine = ...;

Context context = new Context();
context.setVariable("name", "Spring");
context.setVariable("url", "http://spring.io");
context.setVariable("tags", "#framework #java #spring".split(" "));

String text = textTemplateEngine.process("text-template", context);

text variable will contain the output of processing /templates/text/text-template.txt

More on textual syntax

Source code

See pl.codeleak.demos.sbt.thymeleaf.ThymeleafTextTemplates class for the complete example. Repository: https://github.com/kolorobot/spring-boot-thymeleaf

1 comment:

  1. An interesting solution, is it possible to also work with text blocks on the site made on HTML5 template. I need to transfer several text blocks from joomla to HTML5, but when integrating the text incorrectly displayed, in an encrypted form. I have not yet been able to eliminate this problem

    ReplyDelete