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

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

import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
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();
		ve.init();

		// 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() );
	}
}

Output
When you compile and run,the output will be;

My name is Velocity

Note:
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();
velocityProperties.setProperty("file.resource.loader.path",
    "/path/to/my/velocity/template/dir");

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

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

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

Example:

#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.

Advertisements