Text and HTML templates

suggest change

A template is text with holes in it: you write the fixed parts once and fill in the holes with data at runtime. Templates are used for emails, reports, generated config files, code generation and, most often, HTML pages.

The JDK has no template engine. What it does have:

For anything with loops, conditions, includes or HTML output, use a library. The common choices are Mustache, FreeMarker, Thymeleaf, Pebble and jte.

Java 21 and 22 had string templates (STR."Hello \{name}") as a preview feature. They were removed in Java 23 and are not part of the language, so don't use them.

Text blocks and formatted

For a fixed layout with a few values, a text block plus formatted is often all you need:

String name = "Alice";
int count = 3;
double total = 41.5;

String email = """
    Hi %s,

    Your order of %d items ships today.
    Total: $%.2f

    Thanks!
    """.formatted(name, count, total);
System.out.print(email);
Hi Alice,

Your order of 3 items ships today.
Total: $41.50

Thanks!

The downsides: placeholders are positional, so with more than a few values it is easy to swap two of them. The template has to live in Java source, and nothing is escaped. See String formatting for the full format syntax.

Repeated parts are built in Java code, for example with a stream:

import java.util.List;
import java.util.stream.Collectors;

record Item(String name, int qty) {}

List<Item> items = List.of(new Item("Pen", 2), new Item("Notebook", 1));

String lines = items.stream()
    .map(it -> "  - %-10s x%d".formatted(it.name(), it.qty()))
    .collect(Collectors.joining("\n"));

String text = """
    Items:
    %s
    """.formatted(lines);
System.out.print(text);
Items:
  - Pen        x2
  - Notebook   x1

A minimal ${name} template engine

Named placeholders are much easier to read than %s. Matcher.replaceAll(Function) (Java 9+) turns this into a few lines:

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MiniTemplate {
    private static final Pattern VAR = Pattern.compile("\\$\\{(\\w+)}");

    static String render(String template, Map<String, ?> vars) {
        return VAR.matcher(template).replaceAll(m -> {
            String key = m.group(1);
            if (!vars.containsKey(key)) {
                throw new IllegalArgumentException("missing variable: " + key);
            }
            // quoteReplacement: values may contain '$' or '\'
            return Matcher.quoteReplacement(String.valueOf(vars.get(key)));
        });
    }

    public static void main(String[] args) {
        String tpl = "Dear ${name}, your balance is ${balance}.";
        System.out.println(render(tpl, Map.of("name", "Bob", "balance", "$12.30")));
        render(tpl, Map.of("name", "Bob"));
    }
}
Dear Bob, your balance is $12.30.
Exception in thread "main" java.lang.IllegalArgumentException: missing variable: balance

Two details matter here:

Each value is replaced exactly once, so a value that contains ${...} is not expanded again. That makes this safe for user-supplied values.

Apache Commons Text StringSubstitutor

If you already use Apache Commons Text, StringSubstitutor does the same with more features: default values, nested variables, and lookups of system properties or environment variables.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.15.0</version>
</dependency>
import java.util.Map;
import org.apache.commons.text.StringSubstitutor;

Map<String, Object> values = Map.of("user", "Alice", "count", 5);
StringSubstitutor sub = new StringSubstitutor(values);

System.out.println(sub.replace("${user} has ${count} new messages"));
System.out.println(sub.replace("Theme: ${theme:-light}")); // default value after :-
System.out.println(sub.replace("Unknown ${missing} stays"));

sub.setEnableUndefinedVariableException(true);
sub.replace("${missing}"); // throws IllegalArgumentException
Alice has 5 new messages
Theme: light
Unknown ${missing} stays

Note the default: an unknown variable is left in the output unchanged. Turn on setEnableUndefinedVariableException(true) to make it an error.

HTML templates must escape

As soon as the output is HTML, every value inserted into the page must be escaped. Otherwise a user named <script>alert(1)</script> runs JavaScript in the browser of everyone who views their profile. This is cross-site scripting (XSS), one of the most common web vulnerabilities.

The minimal escaping for HTML text and quoted attribute values replaces 5 characters:

static String escapeHtml(String s) {
    StringBuilder sb = new StringBuilder(s.length() + 16);
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        switch (c) {
            case '&' -> sb.append("&amp;");
            case '<' -> sb.append("&lt;");
            case '>' -> sb.append("&gt;");
            case '"' -> sb.append("&quot;");
            case '\'' -> sb.append("&#39;");
            default -> sb.append(c);
        }
    }
    return sb.toString();
}

String comment = "<script>alert('hi')</script> & bye";
System.out.println("<p>" + escapeHtml(comment) + "</p>");
<p>&lt;script&gt;alert(&#39;hi&#39;)&lt;/script&gt; &amp; bye</p>

& must be handled, otherwise &lt; typed by a user would show up as <. Escaping quotes matters for attributes: <input value="..."> with an unescaped " lets the value close the attribute and add new ones.

Library options:

HTML escaping is only correct for HTML text and quoted attributes. A value placed inside a <script> block, a style attribute, an unquoted attribute or a URL like href="..." needs different encoding. A javascript:alert(1) URL contains nothing that HTML escaping changes. Validate URLs (for example, allow only http and https) before putting them in href or src.

Escaping by hand is easy to forget in one place out of hundreds. This is the main reason to use a template engine that escapes by default: you have to do something explicit to output raw HTML.

Mustache

Mustache is a "logic-less" template language: there are no if statements or expressions in the template, only variables and sections. The same syntax is implemented in many languages, so templates can be shared between a Java backend and a JavaScript frontend. The most used Java implementation is mustache.java:

<dependency>
    <groupId>com.github.spullara.mustache.java</groupId>
    <artifactId>compiler</artifactId>
    <version>0.9.14</version>
</dependency>
import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;

public class MustacheDemo {
    public static void main(String[] args) {
        String template = """
            <h1>Hello {{name}}</h1>
            {{#items}}
            <li>{{title}}: {{price}}</li>
            {{/items}}
            {{^items}}
            <p>Your cart is empty.</p>
            {{/items}}
            """;

        MustacheFactory mf = new DefaultMustacheFactory();
        Mustache mustache = mf.compile(new StringReader(template), "cart");

        Map<String, Object> data = Map.of(
            "name", "<Bob & Co>",
            "items", List.of(
                Map.of("title", "Pen", "price", "1.50"),
                Map.of("title", "Book", "price", "12.00")));

        StringWriter out = new StringWriter();
        mustache.execute(out, data);
        System.out.print(out);
    }
}
<h1>Hello &lt;Bob &amp; Co&gt;</h1>
<li>Pen: 1.50</li>
<li>Book: 12.00</li>

The tags:

Data can be a Map, or any object: mustache.java finds name via a method name(), getName(), isName() or a field.

With new DefaultMustacheFactory("templates"), mf.compile("cart.mustache") loads the file from the templates directory on the classpath (see Resources on classpath). The factory caches compiled templates and the compiled Mustache is thread-safe, so create both once and reuse them.

Because templates have no logic, you prepare the data in Java: format prices, compute flags like hasDiscount, sort lists. Many people consider that a feature, since the template stays simple and the logic is testable.

FreeMarker

FreeMarker is an older, very capable engine with its own expression language: conditions, loops, macros, built-in functions for strings, numbers and dates, and template inheritance via includes and macros. It is used for web pages, emails and code generation.

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.35</version>
</dependency>
import freemarker.core.HTMLOutputFormat;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class FreeMarkerDemo {
    public record Product(String name, BigDecimal price, boolean onSale) {}

    public static void main(String[] args) throws Exception {
        // create one Configuration per application and reuse it
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_35);
        cfg.setDefaultEncoding("UTF-8");
        cfg.setLocale(Locale.US);
        cfg.setOutputFormat(HTMLOutputFormat.INSTANCE); // auto-escape ${...}
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        String src = """
            <h1>${title}</h1>
            <ul>
            <#list products as p>
              <li>${p.name} - $${p.price?string("0.00")}<#if p.onSale> (sale!)</#if></li>
            <#else>
              <li>No products</li>
            </#list>
            </ul>
            <p>${footer!"no footer"}</p>
            """;
        Template t = new Template("products", new StringReader(src), cfg);

        Map<String, Object> model = Map.of(
            "title", "Tools & Toys",
            "products", List.of(
                new Product("Hammer", new BigDecimal("9.5"), false),
                new Product("Kite <XL>", new BigDecimal("24"), true)));

        StringWriter out = new StringWriter();
        t.process(model, out);
        System.out.print(out);
    }
}
<h1>Tools &amp; Toys</h1>
<ul>
  <li>Hammer - $9.50</li>
  <li>Kite &lt;XL&gt; - $24.00 (sale!)</li>
</ul>
<p>no footer</p>

Things to know:

Instead of setting the output format explicitly, you can name template files with the .ftlh extension (HTML, auto-escaped) or .ftlx (XML); .ftl files are not escaped. To load templates from the classpath:

cfg.setClassForTemplateLoading(FreeMarkerDemo.class, "/templates");
Template page = cfg.getTemplate("page.ftlh"); // cached after the first call

Configuration and Template are thread-safe once configured. Don't create a new Configuration per request: it holds the template cache.

Thymeleaf

Thymeleaf is the standard template engine in Spring Boot web apps. Its templates are valid HTML: the dynamic parts are attributes such as th:text, so a designer can open the file in a browser and see the placeholder content. It also works without Spring:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.1.5.RELEASE</version>
</dependency>
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.StringTemplateResolver;

public class ThymeleafDemo {
    public static void main(String[] args) {
        StringTemplateResolver resolver = new StringTemplateResolver();
        resolver.setTemplateMode(TemplateMode.HTML);

        TemplateEngine engine = new TemplateEngine();
        engine.setTemplateResolver(resolver);

        String template = """
            <h1 th:text="${user}">Placeholder name</h1>
            <p th:if="${#lists.isEmpty(items)}">Nothing here.</p>
            <ul th:unless="${#lists.isEmpty(items)}">
              <li th:each="item : ${items}" th:text="${item.name}">Sample item</li>
            </ul>
            <a th:href="${profileUrl}">Profile</a>
            """;

        Context ctx = new Context(Locale.US);
        ctx.setVariable("user", "<Bob>");
        ctx.setVariable("items", List.of(Map.of("name", "Pen"), Map.of("name", "Ink")));
        ctx.setVariable("profileUrl", "/users?id=7&tab=info");

        System.out.print(engine.process(template, ctx));
    }
}

The output (the exact whitespace around the repeated <li> elements may differ):

<h1>&lt;Bob&gt;</h1>

<ul>
  <li>Pen</li>
  <li>Ink</li>
</ul>
<a href="/users?id=7&amp;tab=info">Profile</a>

Thymeleaf uses SLF4J for logging. Add a binding such as slf4j-simple or Logback, otherwise SLF4J prints a warning on startup. In a real application use a ClassLoaderTemplateResolver with a prefix like templates/ and suffix .html, and create the TemplateEngine once. It caches parsed templates and is thread-safe.

Other engines

Choosing

Need Use
A few values in a fixed text text block + formatted
Named placeholders, no loops small regex replacer or StringSubstitutor
Localized messages, plurals MessageFormat with resource bundles
Simple HTML or email templates shared with JavaScript Mustache
Emails, reports, code generation, complex logic in templates FreeMarker or Pebble
Spring web pages, templates designers edit as HTML Thymeleaf
Type-checked templates, maximum speed jte

Whatever you choose:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents