Saturday, February 22, 2014

Velocity without template(.vm) file

Velocity can be used without a .vm file.
The original template string could be stored in other places, eg. database, or coded in java class.

But there are slightly different to merge the template string with the passed in parameters.

Below is the sample code.
// template string coded in java class or retrieve from database
String templateString = "Using $project $name without vm file.";

// initialize Velocity
VelocityContext context = new VelocityContext();
context.put("name", "Velocity");
context.put("project", "Jakarta");

String output = new StringWriter();

// evaluate the template string and merge them together
Velocity.evaluate(context, output, "log or null", templateString);
System.out.println("output: " + output);

***to use Velocity with .vm file, we use template.merge( context, output )
***to use Velocity without .vm file, we use Velocity.evaluate( context, output, logTag, templateString )


Done!!

LinkWithin

Related Posts Plugin for WordPress, Blogger...