2.2 Velocity Template Language (VTL): An Introduction

The Velocity Template Language (VTL) is meant to provide an easy, simple and clean way to incorporate dynamic content in a web page. Even a web page developer with little or no programming experience should soon be capable of using VTL to incorporate dynamic content in a web site.

VTL uses references to embed dynamic content in a web site, and a variable is one type of reference. They can refer to something defined in the Java code, or it can get its value from a VTL statement in the web page itself.

Example 2.1. A simple VTL statement

#set( $a = "Velocity" )

This VTL statement, like all VTL statements, begins with the # character and contains a directive: set. When an online visitor requests your web page, the Velocity Templating Engine will search through your web page to find all # characters, then determine which mark the beginning of VTL statements, and which of the # characters that have nothing to do with VTL.

The # character is followed by a directive, set. The set directive uses an expression (enclosed in brackets) -- an equation that assigns a value to a variable. The variable is listed on the left hand side and its value on the right hand side; the two are separated by an = character.

In the example above, the variable is $a and the value is Velocity. This variable, like all references, begins with the $ character. String values are always enclosed in quotes, either single or double quotes. Single quotes will ensure that the quoted value will be assigned to the reference as is. Double quotes allow you to use velocity references and directives to interpolate, such as "Hello $name", where the $name will be replaced by the current value before that string literal is assigned to the left hand side of the =.

The following rule of thumb may be useful to better understand how Velocity works: References begin with $ and are used to get something. Directives begin with # and are used to do something.

In the example above, #set is used to assign a value to a variable. The variable, $a, can then be used in the template to output Velocity.