The Template API allows you to put variables in your configuration files; the variables are interpreted at runtime, and their values can be specified in an application-specific manner.


A Simple example

Using the Template API can be summarized as follows:

The following code illustrates how to use the API:

// template-related classes are imported 
// from org.sapia.util.text

String toRender = "your current directory: ${user.dir}";
TemplateFactory fac = new TemplateFactory();
TemplateContextIF ctx = new SystemContext();
TemplateElementIF template = fac.parse(toRender);

The above will display your current directory (corresponding to the "user.dir" system property).

How It Works

The template factory parses a template element out of a given string content. The template element is the actual object representation of the string content; it can be kept in memory, without the content needing to be reparsed prior to each use. The template element is used to "render" its content, given a context that contains values used internally for variable interpolation.

What's in a Context?

The TemplateContextIF interface simply models bindings of name/value pairs that are used for variable interpolation. When using the API, you will often want to implement your own TemplateContextIF. There are two implementations provided as part of the API:

  • SystemContext: implements its behavior on top of the Java system properties.
  • MapContext: implements its behavior over a Map instance.

The TemplateContextIF interface is quite simple:

public interface TemplateContextIF {

  public Object getValue(String aName);
  public void put(String name, Object value);

The required methods are semantically identical to their get/put counterparts in the java.util.Map interface.


Use the template API to put variables in configuration files (or in other types of files); the variables are interpolated at runtime through an application-defined context.