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:


  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


Post a Comment

Popular posts from this blog

Different ways of validating @RequestBody in Spring MVC with @Valid annotation