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

public static class ThymeleafConfig {

    @Bean(name = "textTemplateEngine")
    public TemplateEngine textTemplateEngine() {
        TemplateEngine templateEngine = new TemplateEngine();
        return templateEngine;

    private ITemplateResolver textTemplateResolver() {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        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})]
[# th:each="tag : ${tags}" ]

Process the template

TemplateEngine textTemplateEngine = ...;

Context context = new Context();
context.setVariable("name", "Spring");
context.setVariable("url", "");
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:

Popular posts from this blog

Parameterized tests in JavaScript with Jest