Using Velocity Templates

October 5, 2010

Here's how to process a Velocity (http://velocity.apache.org/) template in Java code

First we need to set up properties to pass to the velocity processor. This will ensure the classpath is searched the the specified template.

// setup velocity environment
Properties lProperties = new Properties();
lProperties.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

Next we need a VelocityContext instance, which is the variables that are to be made available in the template.

VelocityContext lVelocityContext = new VelocityContext();
lVelocityContext.put("today", new DateStructure());
lVelocityContext.put("ApplicationStructure", this.application);
lVelocityContext.put("ResponseStructure", this.response);

This example means that $today, $ApplicationStructure and $ResponseStructure are all available to be used in the template.

Next we process the template, picking up the template from a file in the classpath:

StringWriter lOutput = new StringWriter();
try
{
  Velocity.init(lProperties);
  Velocity.mergeTemplate("com/company/csv/CsvToXml.vm", "ISO-8859-1", lVelocityContext, lOutput);
}
catch (Exception lEx)
{
  throw new RuntimeException("Problems running velocity template, underlying error is " + lEx.getMessage(), lEx);
}

Merging From a String

If you already have the template in a String, you can use Velocity.evaluate() to process the template:

Velocity.evaluate(lVelocityContext, lOutput, "LOG", lTemplateContents);

Tags: java velocity