A template abstraction for Spring for rendering text templates in a variety of formats, borrowing heavily from Spring Restdocs where similar concepts are found for generating snippets of documentation in tests.
Two central interfaces are the template, which can render with a provided context:
public interface Template {
String render(Map<String, Object> context);
}
and a template resolver that maps String paths to templates:
public interface TemplateResolver {
Template resolve(String path, MimeType type, Locale locale);
default Template resolve(String path) {
return resolve(path, MimeTypeUtils.ALL, Locale.getDefault());
}
}
Implementations are provided for a variety of template formats, including:
- FreeMarker
- Mustache (via JMustache)
- Thymeleaf
- Antlr String Templates
SimpleTemplate
is a dependency-free option with${placeholder}
syntaxStringTemplate
is also dependency-free, and renders by simply callingtoString()
on the context object- JStachio (reflection-free Mustache templates)
The "string" and "jstachio" options both render Java objects directly, so they don't require a template file (although it is an option with JStachio). The others require a template file on the classpath or other resource location, which is resolved by a TemplateResolver
. A TemplateResolver
is provided for "string" and "jstachio" templates that use a convention that the template is itself part of the model,
which is artificial, but ensures compatibility with the other implementations.