Velocity Template
Velocity Template
Language
What is velocity?
Velocity is java based template engine.
It permits webpage designers to reference
methods defined in java code.
Velocity separates java code from web
pages making the web site more
maintainable in the long run providing a
viable alternative to JSPs.
Velocity can be used to generate web
pages, SQL, PostScript and other output
from templates.
Pre-requisites
Import statements
Import velocity libraries.
Place velocity.properties file in web-inf
The template root path for the
velocity.libararies should be defined in
velocity.properties file.
Velocity Usage
<HTML>
<BODY>
Hello $customer.Name!
<table>
#foreach( $steel in $steelOnSpecial )
#if ($customer.hasPurchased($steel))
<tr>
<td>
$flag.getPromo ($steel)
</td>
</tr>
#end
#end
</table>
Velocity Introduction
VTL uses references to embed dynamic
content to web pages. Variable is one type of
reference.
#set( $a = "Velocity" )
# character marks the beginning of VTL
statements.
String values are always enclosed in quotes
either in single or double quotes.
Double quotes allows to use velocity
references and directives to interpolate.
e.g. “Hello $name”
Thumb Rule
References begin with $ and used to get
something.
Directives begin with # and are used to do
something.
<html>
<body>
#set( $foo = "Velocity" )
Hello $foo World!
</body>
</html>
References
Three type of references in the VTL.
Variables, properties and methods.
Everything coming to and from a
reference is treated as a String object.
If there is an object that represents $foo
(such as an Integer object), then Velocity
will call its .toString() method to resolve
the object into a String.
Variables
Theshorthand notation of a variable consists of a leading "$"
character followed by a VTL Identifier.
alphabetic (a .. z, A .. Z)
numeric (0 .. 9)
hyphen ("-")
underscore ("_")
e.g.
$foo
$mudSlinger
$mud-slinger
$mud_slinger
$mudSlinger1
Properties
The shorthand notation consists of a leading $
character followed a VTL Identifier, followed by
a dot character (".") and another VTL Identifier.
e.g.
$customer.Address
$purchase.Total
$customer.Address returns the value associated
with the key Address. It can also refer to a method
in java class such as getAddress().
Its also an abbreviated way of writing
$customer.getAddress().
Methods
Methods are references that consist of a leading "$" character
followed a VTL Identifier, followed by a VTL Method Body.
A VTL Method Body consists of a VTL Identifier followed
by an left parenthesis character ("("), followed by an optional
parameter list, followed by right parenthesis character (")").
$customer.getAddress()
$page.setTitle( "My Home Page" )
$person.setAttributes( ["Strange", "Weird", "Excited"] )
The Property $customer.Address has the exact same effect as
using the Method $customer.getAddress(). It is generally
preferable to use a Property when available.
The main difference between Properties and Methods is that
you can specify a parameter list to a Method.
Property Lookup Rules
The exact lookup sequence for lower-case names,
such as $customer.address, the sequence is
- getaddress()
- getAddress()
- get("address")
- isAddress()
For upper-case property names like
$customer.Address, it is slightly different:
- getAddress()
- getaddress()
- get("Address")
- isAddress()
Formal Reference Notation
Suppose you were constructing a sentence on the
fly where $vice was to be used as the base word in
the noun of a sentence.
"Jack is a pyromaniac." or “Jack is a
kleptomaniac.”
e.g.
1.Jack is a $vicemaniac. ( velocity fails)
2.Jack is a ${vice}maniac.(legal) here velocity
knows that $vice is the reference and not
$vicemaniac
Formal notation is often useful when references are
directly adjacent to text in a template.
Quiet Reference Notation
When Velocity encounters an undefined reference, its
normal behaviour is to output the image of the
reference.
e.g.
<input type="text" name="email“ value="$email"/>
Here when the form loads the variable reference
$email has no value.
<input type="text" name="email" value="$!email"/>
Here when the form loads an empty string will be the
output.
Formal and quiet reference notation can be used
together, as demonstrated below.
<input type="text" name="email" value="$!{email}"/>
Directives
Easy to use script elements that can be used
to creatively manipulate the output of Java
code.
#set
The #set directive is used for setting the
value of a reference.
#set( $primate = "monkey" )
#set( $customer.Behavior = $primate )
The left hand side (LHS) of the assignment
must be a variable reference or a property
reference.
#set
#set( $monkey = $bill ) ## variable reference
#set( $monkey.Friend = "monica" ) ## string literal
#set( $monkey.Blame = $whitehouse.Leak ) ## property
reference
#set( $monkey.Plan = $spindoctor.weave($web) ) ## method
reference
#set( $monkey.Number = 123 ) ##number literal
#set( $monkey.Say = ["Not", $my, "fault"] ) ## ArrayList
#set( $monkey.Map = {"banana" : "good", "roast beef" :
"bad"}) ## Map
#if & #else
The #if directive in Velocity allows for text to be
included when the web page is generated, on the
conditional that the if statement is true.
#if( $foo )
<strong>Velocity!</strong>
#end
An #elseif or #else element can be used with an
#if element.
Note that the Velocity Templating Engine will
stop at the first expression that is found to be true.
Relational Operator
Velocity uses the equivalent operator to determine
the relationships between variables.
#set ($foo = "deoxyribonucleic acid")
#set ($bar = "ribonucleic acid")
#if ($foo == $bar)
In this case it's clear they aren't equivalent. So...
#else
They are not equivalent and this will be the output.
#end
In Velocity the equivalent operator can be used to
directly compare numbers, strings, or objects.
In Java where == can only be used to test object
equality.
Logical Operators
Logical AND
## logical AND
#if( $foo && $bar )
<strong> This AND that</strong>
#end
Logical OR
## logical OR
#if( $foo || $bar )
<strong>This OR That</strong>
#end
Logical NOT
##logical NOT
#if( !$foo )
<strong>NOT that</strong>
#end
Foreach Loop
The #foreach loop causes the $allProducts list (the object) to be looped
over for all of the products (targets) in the list. Each time through the loop,
the value from $allProducts is placed into the $product variable.
<ul>
#foreach( $product in $allProducts )
<li>$product</li>
#end
</ul>
Velocity provides an easy way to get the loop counter so that you can do
something like the following:
<table>
#foreach( $customer in $customerList )
<tr><td>$velocityCount</td><td>$customer.Name</td></tr>
#end
</table>
Loop counter settings
The default name for the loop counter variable reference,
which is specified in the velocity.properties file, is
$velocityCount. By default the counter starts at 1, but this can
be set to either 0 or 1 in the velocity.properties file.
# Default name of the loop counter
# variable reference.
directive.foreach.counter.name = velocityCount
# Default starting value of the loop
# counter variable reference.
directive.foreach.counter.initial.value = 1
It's possible to set a maximum allowed number of times that a
loop may be executed.
# The maximum allowed number of loops.
directive.foreach.maxloops = -1
Velocity macros
The #macro script element allows template designers to
define a repeated segment of a VTL template.
#macro( d )
<tr><td></td></tr>
#end
#d()
When this template is called, Velocity would replace #d()
with a row containing a single, empty data cell.
Velocimacros can be defined inline in a Velocity template,
meaning that it is unavailable to other Velocity templates on
the same web site.
Currently, Velocimacros must be defined before they are first
used in a template.
Velocity macro taking two arguments.
Notice that $greatlakes takes the place of $somelist. When the #tablerows Velocimacro is called
in this situation, the following output is generated:
<table>
<tr><td bgcolor="blue">Superior</td></tr>
<tr><td bgcolor="blue">Michigan</td></tr>
<tr><td bgcolor="blue">Huron</td></tr>
<tr><td bgcolor="blue">Erie</td></tr>
<tr><td bgcolor="blue">Ontario</td></tr>
</table>
velocity.properties
velocimacro.library - VM_global_library.vm
velocimacro.permissions.allow.inline-The default, true,
allows template designers to define Velocimacros in the
templates themselves.
velocimacro.permissions.allow.inline.local.scope-with this
property set to true, a template can define inline VMs that are
usable only by the defining template.
velocimacro.context.localscope-When true, any
modifications to the context via #set() within a Velocimacro
are considered 'local' to the Velocimacro, and will not
permanently affect the context.
velocimacro.library.autoreload-The default value is false.
When set to true the source Velocimacro library for an
invoked Velocimacro will be checked for changes, and
reloaded if necessary.
Other Features
The added advantage of velocity's behavior is to gobble up
excess whitespace.
Velocity has a handful of built-in mathematical functions that
can be used in templates with the set directive.
#set( $foo = $bar + 3 )
#set( $foo = $bar - 4 )
#set( $foo = $bar * 6 )
#set( $foo = $bar / 2 )
#set( $foo = $bar % 5 )
The range operator can be used in conjunction with #set and
#foreach statements.
[n..m]
Both n and m must either be or produce integers.
Range Operator
First example:
#foreach( $foo in [1..5] )
$foo
#end
Second example:
#foreach( $bar in [2..-2] )
$bar
#end
Third example:
#set( $arr = [0..1] )
#foreach( $i in $arr )
$i
#end
String concatenation
e.g.
#set( $size = "Big" )
#set( $name = "Ben" )
#set($clock = "$size$name" )
The clock is $clock.