Skip navigation links

Package net.pterodactylus.util.template

Light-weight template system.

See: Description

Package net.pterodactylus.util.template Description

Light-weight template system.

Writing Templates

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.

Rendering Templates

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.

Setting Template Variables

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);
 

Looping Over Collections

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.

Looping Over Maps

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.)

Loop Properties

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.

Item Properties

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.

Handling Custom Types

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;
        }
 }
 

The Reflection Accessor

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.

Conditional Execution

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.

Filtering Output

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.

Storing Values in the Template

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.

Internationalization / Localization (i18n, l10n)

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.

Whitespace

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

Single quotes preserve all characters until another single quote character is encountered.

Double Quotes

Double quotes preserve all characters until either another double quote or a backslash is encountered.

Backslash

The backslash preserves the next character but is discarded itself.

Examples

 <%= 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.

Skip navigation links

Copyright © 2026. All rights reserved.