Text and HTML templates
suggest changeA 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:
String.formatted/String.formatwith text blocks, for small fixed layoutsjava.text.MessageFormat, for localized messages- regular expressions, which make it easy to write a small
${name}replacer
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:
- The return value of the replacer function is a replacement string, where
$1means "group 1" and\is an escape. WithoutMatcher.quoteReplacement, the value$12.30would be read as "group 1 followed by2.30" and silently come out asbalance2.30. A value ending in\would throwIllegalArgumentException. - Failing on a missing variable is usually better than silently leaving
${balance}in an email sent to a customer.
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("&");
case '<' -> sb.append("<");
case '>' -> sb.append(">");
case '"' -> sb.append(""");
case '\'' -> sb.append("'");
default -> sb.append(c);
}
}
return sb.toString();
}
String comment = "<script>alert('hi')</script> & bye";
System.out.println("<p>" + escapeHtml(comment) + "</p>");
<p><script>alert('hi')</script> & bye</p>
& must be handled, otherwise < 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:
org.apache.commons.text.StringEscapeUtils.escapeHtml4(s): escapes& < > "and turns non-ASCII characters into named entities (ébecomesé). It does not escape', so only use it inside double-quoted attributes.- OWASP Java Encoder (
org.owasp.encoder:encoder): context-specific encoders such asEncode.forHtml,Encode.forHtmlAttribute,Encode.forJavaScriptandEncode.forUriComponent.
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 <Bob & Co></h1>
<li>Pen: 1.50</li>
<li>Book: 12.00</li>
The tags:
{{name}}: the value, HTML-escaped{{{name}}}or{{& name}}: the value without escaping, for HTML you trust{{#items}}...{{/items}}: a section. It repeats for each element of a list, renders once for a truthy value, and is skipped forfalse,nullor an empty list. Inside the section, names are first looked up on the current element{{^items}}...{{/items}}: an inverted section, rendered only whenitemsis missing,falseor empty{{> header}}: includes another template (a partial){{! comment }}: a comment
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 & Toys</h1>
<ul>
<li>Hammer - $9.50</li>
<li>Kite <XL> - $24.00 (sale!)</li>
</ul>
<p>no footer</p>
Things to know:
${expr}inserts a value. With the HTML output format it is escaped automatically.${html?no_esc}outputs it raw.- A
$that is not followed by{is plain text, so$${p.price...}prints a dollar sign followed by the price. To output a literal${, write${"$"}{or wrap the text in<#noparse>...</#noparse>. - A missing or
nullvariable is an error by default.${footer!"no footer"}gives a default, and<#if footer??>tests whether it exists. - Lines that contain only FTL tags (
<#list>,<#else>,</#list>) are removed from the output, so the template can be indented naturally. - Numbers are formatted using the configured locale:
${1234.5}prints1,234.5withLocale.US. Use?cfor machine-readable numbers (for example in JavaScript or URLs), and?string("0.00")for a fixed pattern. - With
incompatible_improvements2.3.33 or later, record components are available as properties (p.name), like JavaBean getters.
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><Bob></h1>
<ul>
<li>Pen</li>
<li>Ink</li>
</ul>
<a href="/users?id=7&tab=info">Profile</a>
th:textreplaces the element's content with the escaped value;th:utextinserts it unescapedth:each,th:ifandth:unlessrepeat or remove the whole element, including its tag#lists,#strings,#numbersand#datesare helper objects for common operations- any
th:xxxattribute sets the attributexxx, with escaping - expressions such as
${item.name}use OGNL when running standalone, and SpEL inside Spring. Both read Map entries and JavaBean getters
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
- Pebble: Twig/Jinja-like syntax (
{{ name }},{% for item in items %}), template inheritance with{% extends %}and blocks, auto-escaping on by default. - jte: templates are compiled to Java classes, so a typo in a variable name or a wrong type is a compile error, not a runtime error. Very fast, with escaping that knows whether a value is in HTML text, an attribute or JavaScript.
- Velocity: older (
$name,#foreach), still found in legacy code. Prefer one of the above for new projects.
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:
- use an engine that escapes HTML by default, and treat every raw-output construct (
{{{x}}},?no_esc,th:utext) as a place to review for XSS - make missing variables an error, at least in tests
- configure the engine once and reuse it; parsing a template is much slower than rendering it
- set the locale explicitly when templates format numbers or dates