Velocity Templating in 3 Steps

Step 1: DOWNLOAD JARS : Download velocity binaries from velocity website, we will need velocity-dep.jar from the zip (for example velocity-1.7-dep.jar)

Step 2: CREATE TEMPLATE : Create a helloworld.vm file and save it into a folder lets say D:/VMtemplates/. Following is the code that goes in the helloworld,vm file.

<html><head>Hello $header</head><body>Hello $name! Welcome to Velocity!</body></html>

Step 3: PROGRAM TO USE ABOVE TEMPLATE : Finally create create a main class( which uses the above template and generates a html file dynamically:



import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

public class HelloWorld
public static void main( String[] args )throws Exception

VelocityEngine ve = new VelocityEngine();

ve.addProperty(“file.resource.loader.path”, “D:/VMtemplates/“);

// next, get the Template
Template t = ve.getTemplate( “helloworld.vm” );

// create a context and add data
VelocityContext context = new VelocityContext();

context.put(“name”, “API LEVEL”);
context.put(“header”, “My Header”);

// now render the template into a StringWriter
StringWriter writer = new StringWriter();

t.merge( context, writer );

// get the html text
String filecontent =writer.toString();

File htmlfile = new File(“D:/VMtemplates/heloworld.html”);

FileWriter fw = new FileWriter(htmlfile);


The important line is indicated by blue text color also the path marked in bold above are important.

NOTE: that this is a very basic code for getting stated with Velocity Template Engine. Do read further.

Further Reading:


About Dominic

J for JAVA more about me :
This entry was posted in Thechy Stuff and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s