| Interface | Description |
|---|---|
| Accessor |
An accessor can access member variables of objects of a given type.
|
| Filter |
Filters can be used to transform the contents of a variable into some other
representation.
|
| Part |
Interface for a part of a template that can be rendered without further
parsing.
|
| Plugin |
Defines a template plugin.
|
| TemplateProvider |
A provider is used to load templates that are included in other templates
when rendering a template.
|
| Theme |
A theme bundles an arbitrary amount of
Templates together and can
perform additional processing around it. |
| ThemeSelector<C extends ThemeSelectorContext> |
Selects themes based on a context.
|
| WhitespaceRemover |
Removes whitespace from non-template tag parts of a
Template. |
| Class | Description |
|---|---|
| AbstractPart |
Abstract implementation of a
Part that adds a line number and column
number which can be used for TemplateExceptions. |
| BasicWhitespaceRemover |
Removes basic whitespace characters from the beginning of a
String. |
| ChainingTemplateProvider | |
| ClassPathTemplateProvider |
Template provider implementation that uses
Class.getResourceAsStream(String) to load templates for inclusion. |
| CollectionSortFilter | |
| ContainsFilter |
Filter implementation that returns a boolean, depending on whether
the object being filtered is contained in a Collection that is given
as parameter to this filter. |
| DateFilter |
Filter implementation that formats a date. |
| DefaultFilter |
Filter implementation that can return fixed values when the input
value is null. |
| DefaultTheme |
Default
Theme implementation that uses a simple
synchronized map to store themes. |
| DeletePlugin |
Plugin that will remove a value from the current
TemplateContext by
setting it to null. |
| FilesystemTemplateProvider |
TemplateProvider implementation that looks for template files in the
filesystem, either at a hardcoded location or a location that is taken from
the template context parameter to
FilesystemTemplateProvider.getTemplate(TemplateContext, String). |
| FormatFilter | |
| HtmlFilter |
Filters HTML by replacing all characters that match a defined HTML entity by
that entity.
|
| InsertFilter |
Filter implementation that works like a ReplaceFilter, only
that the actual replacement value is read from a template variable, which can
be set either using TemplateContext.set(String, Object) or using a
StoreFilter. |
| ListAccessor | |
| MatchFilter |
Filter implementation that compares (for
equality) the data either with a String
(given as parameter “value”) or an object from the TemplateContext
(whose name is given as parameter “key”). |
| ModFilter |
The mod filter performs a modulo operation on the given number and the
parameter “divisor,” adding the optional parameter “offset” to the dividend,
and returns
true if the module operation did not return a rest, i.e. |
| PaginationFilter | |
| PaginationPlugin | |
| ReflectionAccessor |
Accessor implementation that checks the object for a method that
looks like a getter for the requested member name. |
| RemoveFilter |
Filter implementation that can remove elements from a
Collection. |
| ReplaceFilter |
Filter implementation that replaces parts of a value. |
| StoreFilter |
Filter that stores the output of the chain in the
TemplateContext. |
| Template |
Simple container that holds an initial
TemplateContext that can be
used to store filters, accessors, plugins, providers, and template
objects that are used for all render passes of this template. |
| TemplateContext |
A template context bundles together all providers of information that are
necessary to render a template.
|
| TemplateContextFactory |
Default
TemplateContext factory implementation that creates
TemplateContexts with Accessors, Filters,
Plugins, TemplateProviders, and arbitrary objects that are
set on all created TemplateContexts. |
| TemplateContextProvider | |
| TemplateParser |
Parser for
Templates. |
| TemplateParser.FilterDefinition |
Wrapper for the name of a
Filter and its parameters. |
| TemplateParser.Filters |
Convenience class that wraps around a
List of
TemplateParser.FilterDefinitions and can filter an object through all the
filters it contains. |
| TemplatePart | |
| ThemeSelectorContext |
Marker interface for
ThemeSelector contexts. |
| WhitespaceRemover.NoWhitespaceRemover |
WhitespaceRemover implementation that does not actually remove
any whitespace. |
| XmlFilter |
Filters XML by replacing double quotes characters, apostrophes, the less-than
character, the greater-than characters, and the ampersand by their respective
XML entities.
|
| Exception | Description |
|---|---|
| TemplateException |
Exception that is thrown when a
Template can not be rendered because
its input can not be parsed correctly, or when its template variables can not
be parsed or evaluated. |
Inserting values and control structures such as loops into a template uses a syntax that is well-known by other preprocessors, such es PHP or JSPs. For example:
<html> <head> <title> <% title > </title> </head> </html>
This will insert the value of the template variable named “title” into the template.
To render a Template you need a
TemplateContext.
Template template = TemplateParser.parse(new Filter("template.html"));
TemplateContext templateContext = new TemplateContext();
StringWriter writer = new StringWriter();
template.render(templateContext, writer);
Templates do not hold their own data anymore. To achieve thread safety
without having to synchronize on the whole template, the TemplateContext
was introduced. Its intended lifetime is restricted to a single rendering
pass. A TemplateContextFactory can
be used to easily create TemplateContexts that hold the desired
Filters,
Plugins,
Accessors,
TemplateProviders, and objects. Template
contexts can have parent contexts and use those recursively when any kind
of data is requested.
A template has an initial template context. It can be used to set values in the template that never change during the lifetime of the template. Any values that are set on the template are merged into the template context that is used for the current rendering pass, overwriting all other values set in that context or its parent contexts.
Variables in a template are set using the
TemplateContext.set(String, Object) method.
Template template = TempalteParser.parse(new FileReader("template.html"));
TemplateContext templateContext = templateContextFactory.createTemplateContext();
templateContext.set("variable", "value");
templateContext.set("items", Arrays.asList("foo", "bar", "baz"));
template.render(templateContext, outputWriter);
You can set the value of a template variable to an instance of
Collection. This allows you to iterate over the items in said collection:
<ul> <%foreach pointCollection pointItem> <li> Item: <% pointItem> </li> <%/foreach> </ul>This will output the value of each item in the collection.
It is also possible to loop over Maps. The syntax is identical:
<ul> <%foreach itemValues itemValue> <li> <% itemValue.key>: <% itemValue.value> </li> <%/foreach> </ul>
Instead of looping only over the keys or the values of the Map,
the loop will iterate over the Map.Entrys of the map,
requiring you to access the keys by using the “key” property, and the
value by using the “value” property. (This requires that you install
a ReflectionAccessor on your
template context, or a similar Accessor
that allows to access the Map.Entry.)
Each iteration of a loop has numerous properties, such as being the first iteration, or the last, or neither of them. These properties can be accessed in a template.
<%foreach pointCollection pointItem> <%first> The collection contains the following items: <ul> <%/first> <li> Item: <% pointItem> </li> <%last> </ul> <%/last> <%/foreach>
The loop properties that can be accessed in this way are: size,
count (running index from 0 to (size - 1)), first,
last, notfirst, notlast, odd, even.
Template variable names can specify a hierarchy: “item.index” specifies the
member “index” of the value of template variable “item”. The default
template context implementation can only handle getting members of template
variables that contain instances of Map; it is possible
to define member accessors for your own types (see below).
<ul> <%foreach itemCollection item> <li> Item: <a href="item?id=<% item.id>"><% item.name></a> </li> <%/foreach> </ul>
When itemCollection is properly set up this will print each item’s
name with a link to an item page that receives the ID of the item as
parameter. If item does not refer to a Map instance,
a custom accessor (see below) is necessary.
The template system can be extended using
Accessors. An accessor is used to
allow template variable syntax like “object.foo”. Depending on the type of
object the appropriate accessor is used to find the value of the
member “foo” (which can e.g. be retrieved by calling a complicated operation
on object).
With a custom type Item that exposes both an ID and a name (using
getID() and getName() methods), the following
Accessor will allow the above
example to work.
public class ItemAccessor implements Accessor {
public Object get(TemplateContext templateContext, Object object, String member) {
Item item = (Item) object;
if ("name".equals(member)) { return item.getName(); }
if ("id".equals(member)) { return item.getId(); }
return null;
}
}
A very convenient accessor (and good base for custom accessors) is the
ReflectionAccessor. It uses
reflection to find members of an object. Accessing the member “fooData”
would look for the methods “getFooData()”, “isFooData()”, “fooData()”, and
call the first method it can locate without parameters. The value returned
by the method is the value returned to the template.
When writing custom Accessors
it is very convenient to subclass
ReflectionAccessor and only add
members that are not present in the original class, defaulting to calling
“super.get()” when a “standard” member is requested.
With a loop and its constructs (e.g. <%first> or <%even>) you can already shape your formatted text in quite some ways. If for some reason this is not enough you do have another possibility.
<p>
The color is:
<%if color.black>
black
<%elseif color.red>
red
<%elseif ! color.green>
not green
<%else>
green
<%/if>
</p>
At the moment the <%if> directive requires a single argument
which has to evaluate to a Boolean object. The object may
be prepended by an exclamation point (“!”, either with or without
whitespace following it) to signify that the condition should be reversed.
Using a custom accessor this can easily be accomplished. Any further
parsing (and expression evaluation) would make the template parser and
renderer almost infinitely more complex (and very not-light-weight-anymore).
It is also possible to react on the result of a
Filter; see below.
One large issue when handling text in web pages is escaping the HTML code so that the content of a web page does not have the capability of inserting custom code into a web site, or destroying its design by unbalanced tags. The template supports filtering output but does not have any output filters added to it by default.
TemplateContext templateContext = templateContextFactory.createTemplateContext();
templateContext.addFilter("html", new HtmlFilter());
This will a filter for HTML to the list of available filters. If you want to escape some text in your template, apply it using the pipe character (“|”, with or without whitespace around it).
<div>Your name is <% name|html>, right?</div>
You can also use several filters for a single variable output. Those are executed in the order they are specified.
<div>Your name is <% name|html|replace needle=Frank replacement=Steve>, right?</div>
It is also possible to use a filter in an <%if> construct.
<%if name|match value=Frank>You’re Frank!<%else>You’re not Frank.<%/if>
The String conversion of the final filter result has to
match “true” in order to be evaluated as true, so not only
Booleans but any other object can result in an
if-branch being executed.
Sometimes it can be necessary to store a value in the template context for later use. In conjunction with a replacement filter this can be used to include template variables in strings that are output by other filters, e.g. an i18n filter.
<% user | html | store key='htmlUser'>
<% HelloText | i18n | html | insert needle='${user}' key='htmlUser'>
The “insert” filter can also read variables directly from the template.
When creating web pages for larger projects you often have to deal with multiple languages. One possibility to achieve multilingual support in a template system would be to simply ignore language support in the template system and create a new template for each language. However, this solution is not desirable for any of the participating parties: the programmer has to load a different template depending on the language; the designer has to copy a desgin change into every translated template again; the translator needs to copy and process a complete template, potentially missing translatable items in a sea of design markup.
One possible solution is the possibility to hardcode values in the template and run them through arbitrary filters.
<div><%= Item.Name | i18n | html></div> <div><% item.name | html></div> <div><%= Item.ID | i18n | html></div> <div><% item.id | html></div>
In this example the strings “Item.Name” and “Item.ID” are run through a
custom Filter that replaces a
language-independent key into a translated string. To prevent nasty
surprises the translated string is also run through a HTML filter before
the final value is printed on the web page.
Sometimes, e.g. when using <%= or filters, whitespace in a filter
directive needs to be preserved. This can be accomplished by using single
quotes, double quotes, or a backslash.
Single quotes preserve all characters until another single quote character is encountered.
Double quotes preserve all characters until either another double quote or a backslash is encountered.
The backslash preserves the next character but is discarded itself.
<%= foo | replace needle=foo replacement="bar baz">
This will replace the text “foo” with the text “bar baz”.
<%= "foo bar" | replace needle=foo replacement="bar baz">
This will replace the text “foo bar” with the text “bar baz bar”.
<%= "foo bar" | replace needle='foo bar' replacement="bar baz">
This will replace the text “foo bar” with the text “bar baz”.
<%= "foo bar" | replace needle=foo\ bar replacement="bar baz">
This will also replace the text “foo bar” with the text “bar baz”.
<%= "foo bar" | replace needle="foo\ bar" replacement="bar baz">
This will also replace the text “foo bar” with the text “bar baz”.
<%= "foo bar" | replace needle='foo\ bar' replacement="bar baz">
This will not replace the text “foo bar” with anything because the text “foo\ bar” is not found.
Copyright © 2026. All rights reserved.