Velocity Template Engine

Velocity is an open source template engine developed by an international volunteer community and hosted by the Apache Software Foundation.

A template engine is a software that is designed to process web templates and content information to produce output web documents. Any velocity project contains two things – Velocity Template & Java Program.

Velocity Template
A velocity template is a text or text file (with .vm extension – that’s the general practice), that contains normal text and velocity specific placeholders (e.g. $name).

A sample template file testvelocity.vm

My name is $name

A java program that refers to the the testvelocity.vm template.

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class TestVelocity
	public static void main( String[] args )
	throws Exception
		// Initializes engine
		VelocityEngine ve = new VelocityEngine();

		// Getting the Template
		Template temp = ve.getTemplate("testvelocity.vm");

		// Create a context and add data to the template placeholder
		VelocityContext context = new VelocityContext();
		context.put("name", "Velocity");

		// Fetch template into a StringWriter
		StringWriter wr = new StringWriter();
		temp.merge( context, wr );
		System.out.println( wr.toString() );

When you compile and run,the output will be;

My name is Velocity

The template file is expected to be in the class-path. If you want to load a template file, add the following code block to the code.

Properties velocityProperties = new Properties();

// Use this properties to initialize the engine
VelocityEngine ve = new VelocityEngine();

Directives – What is it?
There are different directives for velocity.

#set(), #if(), #else, #elseif(), #end, #foreach(), #include(), #parse(), #macro()


#if ( $value > 10 )
display me. I am greater than 10.
#elseif ( $value < 10 ) display me. I am lesser than 10. #else display me. #end [/sourcecode] I will be adding more about it in my future posts.