Pages

Monday, June 6, 2011

A Brief Look at Apache Velocity




Introduction
Velocity is a template engine. Using Java classes, you can inject objects into template engine and use those injected objects in velocity template (.vm) files.

Its benefits are:
  •  It can be used in desktop applications, web applications and other areas where a structured text or code is required.
  • It can be used as a powerful code generator. Dynamic codes are created by velocity injected objects.
  • It can access all public attribute and methods of given object.
  •  It has an easy and clear syntax.
  • You can define user interfaces (HTML, JSP etc.) dynamically and developers and designers can work seperately. So, MVC pattern can be used too.
Examples
Here is an example velocity template file helloWorld.vm:

Hello $param


And below is an example Java file HelloWorld.java that uses the template:

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import java.io.StringWriter;

public class HelloWorld
{
    public static void main( String[] args ) throws Exception
    {
        /*  first, get and initialize an engine  */
        VelocityEngine engine = new VelocityEngine();
        engine.init();
        Template template = engine.getTemplate( "helloWorld.vm" );
        VelocityContext context = new VelocityContext();
        context.put("param", "World");
        StringWriter writer = new StringWriter();
        template.merge( context, writer );
        System.out.println( writer.toString() );    
    }
}
Console Result: Hello World

In the code Velocity engine is created, initialized, velocity tamplate file template is taken, required parameters are put into context, and at last the string is written to the screen.

Commands
Velocity also has a built-in VTL (Velocity Template Language) syntax that has following statements:

VTL Tags

Escape Tool
Because of the VTL is a template language, string operations are required widely. For that case, some escaping methods are supported for java, javascript, html, xml, sql and some character renderings exist: 

For example,
$val = “Stop!”
$esc.java($java)
produces \”Stop!\”
or
${esc.d} produces $ output.
${esc.h} produces # output.

2 comments:

  1. Macro devs also close with and #end directive.

    Kind of light on info.

    ReplyDelete
  2. Corrected. Thanks for the warning.

    ReplyDelete