Velocity Templating in 3 Steps


Step 1: DOWNLOAD JARS : Download velocity binaries from velocity website http://velocity.apache.org, 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(HelloWorlf.java) which uses the above template and generates a html file dynamically:

package hello.world;

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;

import org.apache.velocity.app.VelocityEngine;
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”);
if(!htmlfile.exists()){
htmlfile.createNewFile();
}

FileWriter fw = new FileWriter(htmlfile);
fw.write(filecontent);
fw.close();

}
}

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:

http://velocity.apache.org/engine/devel/webapps.html

http://velocity.apache.org/engine/devel/developer-guide.html

Advertisement

About Dominic

J for JAVA more about me : http://about.me/dominicdsouza
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:

WordPress.com Logo

You are commenting using your WordPress.com 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