Apache Velocity is a free, simple and powerful template engine written in 100% pure Java.
This requires the libraries velocity-1.7.jar, oro-2.0.8.jar, commons-lang-2.4.jar,
commons-collections-3.2.1.jar, commons-logging-1.1.jar, log4j-1.2.12.jar to be in classpath.
The following example shows creating and iterating map variables.
/**
* Initialize engine and get template
*/
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
Template template = ve.getTemplate("map_variables.vm");
/**
* Prepare context data
*/
VelocityContext context = new VelocityContext();
/**
* Merge data and template
*/
StringWriter swOut = new StringWriter();
template.merge(context, swOut);
System.out.println(swOut);
}
}
It gives the following output,
Key Set : [1, 2, 3, 4]
Values : [ONE, TWO, THREE, FOUR]
Key : 1 and value : ONE
Key : 2 and value : TWO
Key : 3 and value : THREE
Key : 4 and value : FOUR
Key : 1 and value : ONE
Key : 2 and value : TWO
Key : 3 and value : THREE
Key : 4 and value : FOUR
Student name : Sriram
Student age : 4