Velocity Engine

Docs

Developers

Community

Translations (outdated)

Velocity News Feed

VTL Reference - Contents

About this Guide

This guide is the reference for the Velocity Template Language (VTL). For more information, please also refer to the Velocity User Guide.

Notations are given in a very approximative EBNF-like syntax, the goal is to remain readable.

References

In the following syntax references, identifier refers to:

( a..z | A..Z | _ ) [ ( a..z | A..Z | 0..9 | _ ) , ( a..z | A..Z | 0..9 | _ ), ... ]

that is, a letter or an underscore followed by any number of letters, numbers and underscores.

If the parser.allow_hyphen_in_identifiers configuration value is set to true, then the - hyphen is also allowed in identifiers (and must be surrounded by spaces to be interpreted as an arithmetic minus operator).

Variables

Notation:

$ [ ! ] [ { ] identifier [ [ | alternate value ] } ]

Usage:

  • alternate value: alternate expression to use if the reference is null, empty, false or zero

Examples:

  • Shorthand notation: $mudSlinger_9
  • Silent Shorthand notation: $!mudSlinger_9
  • Formal notation: ${mudSlinger_9}
  • Silent Formal notation: $!{mudSlinger_9}
  • Alternate value: ${mudSlinger_9|$otherWheels}

Note that for backward compatibility reasons, it's possible to enable '-' as a valid character in variables identifiers, see the parser configuration section.

Properties

Notation:

$ [ { ] identifier . identifier [ [ | alternate value ] } ]

Usage:

  • alternate value: alternate expression to use if the property is null, empty, false or zero

Examples:

  • Regular Notation: $customer.Address
  • Formal Notation: ${purchase.Total}
  • Alternate Value: ${person.name|'John Doe'}

Methods

Notation:

$ [ { ] identifier . identifier ( [ parameter list... ] ) [ [ | alternate value ] } ]

Usage:

  • alternate value: alternate expression to use if the method returns null, empty, false or zero
  • parameter list: optional coma-separated list of expressions

Examples:

  • Regular Notation: $customer.getAddress()
  • Formal Notation: ${purchase.getTotal()}
  • Regular Notation with Parameter List: $page.setTitle( "My Home Page" )
  • Alternate value: ${page.getTitle()|'Blank Page'}

VTL Properties can be used as a shorthand notation for VTL Methods that take get and set. Either $object.getMethod() or $object.setMethod() can be abbreviated as $object.Method. 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.

Each method argument can be any valid VTL expression.

Directives

#set - Establishes the value of a reference

Format:

# [ { ] set [ } ] ( $ref = [ ", ' ] arg [ ", ' ] )

Usage:

  • $ref - The LHS of the assignment must be a variable reference or a property reference.
  • arg - The RHS of the assignment, arg is parsed (i.e. interpolated) if enclosed in double quotes, and not parsed if enclosed in single quotes. If the RHS evaluates to null, it is not assigned to the LHS.

Examples:

  • Variable reference: #set( $monkey = $bill )
  • String literal: #set( $monkey.Friend = 'monica' )
  • Property reference: #set( $monkey.Blame = $whitehouse.Leak )
  • Method reference: #set( $monkey.Plan = $spindoctor.weave($web) )
  • Number literal: #set( $monkey.Number = 123 )
  • Range operator: #set( $monkey.Numbers = [1..3] )
  • Object list: #set( $monkey.Say = ["Not", $my, "fault"] )
  • Object map: #set( $monkey.Map = {"banana" : "good", "roast beef" : "bad"})

The RHS can also be a simple arithmetic expression, such as:

  • Addition: #set( $value = $foo + 1 )
  • Subtraction: #set( $value = $bar - 1 )
  • Multiplication: #set( $value = $foo * $bar )
  • Division: #set( $value = $foo / $bar )
  • Remainder: #set( $value = $foo % $bar )

#if/#elseif/#else - Output conditional on truth of statements

Format:

# [ { ] if [ } ] ( condition ) output [# [ { ] elseif [ } ] ( condition ) output ] [ # [ { ] else [ } ] output ] # [ { ] end [ } ]

Usage:

  • condition - Expression to evaluate. When its result is null, evaluate to false. Otherwise, check for conversion towards Boolean and non-emptiness as follow:

    • return its value for a Boolean object, or the result of the getAsBoolean() method if it exists.
    • if directive.if.empty_check = false (true by default), stop here and consider it true.
    • return whether an array is empty.
    • return whether isEmpty() is false (covers String and all Collection classes).
    • return whether length() is zero (covers CharSequence classes other than String).
    • returns whether size() is zero (covers all Collection classes).
    • return whether a Number strictly equals zero.
    • return whether the result of getAsString() is empty (and false for a null result) if it exists.
    • return whether the result of getAsNumber() strictly equals zero (and false for a null result) if it exists.
    • consider the condition is true
  • output - May contain VTL.

Examples (showing different operators):

Operator Name Symbol Alternative Symbol Example
Equals Number == eq #if( $foo == 42 )
Equals String == eq #if( $foo == "bar" )
Object Equivalence == eq #if( $foo == $bar )
Not Equals != ne #if( $foo != $bar )
Greater Than > gt #if( $foo > 42 )
Less Than < lt #if( $foo < 42 )
Greater Than or Equal To >= ge #if( $foo >= 42 )
Less Than or Equal To <= le #if( $foo <= 42 )
Boolean NOT ! not #if( !$foo )

Notes:

  1. The == operator can be used to compare numbers, strings, objects of the same class, or objects of different classes. In the last case (when objects are of different classes), if at least one the two objects cannot be converted to a number, the toString() method is called on each object and the resulting Strings are compared.
  2. You can also use brackets to delimit directives. This is especially useful when text immediately follows an #else directive.
    #if($foo == $bar)it's true!#{else}it's not!#end
    

#foreach - Loops through a list of objects

Format:

# [ { ] foreach [ } ] ( $ref in arg ) statements [ # [ { ] else [ } ] alternate statements ] # [ { ] end [ } ]

Usage:

  • $ref - The first variable reference is the item.
  • arg - May be one of the following: a reference to a list (i.e. object array, collection, or map), an array list, or the range operator.
  • statements - What is output each time Velocity finds a valid item in the list denoted above as arg. This output is any valid VTL and is rendered each iteration of the loop.
  • alternate statements - What is to display whenever Velocity did not enter the loop (when arg is null, empty, or doesn't have any valid iterator).

Examples of the #foreach loop:

  • Reference: #foreach ( $item in $items ) $item #else no item #end
  • Array list: #foreach ( $item in ["Not", $my, "fault"] ) $item #end
  • Range operator: #foreach ( $item in [1..3] ) $item #end

Inside the #foreach loop, the following can be used:

  • $foreach.count : 1-based loop index
  • $foreach.index : 0-based loop index
  • $foreach.first : true on the first iteration
  • $foreach.last : true on the last iteration
  • $foreach.hasNext : false on the last iteration
  • $foreach.stop() : exists the loop, synonym for #break

The maximum allowed number of loop iterations can be controlled engine-wide with velocity.properties. By default, there is no limit:

# The maximum allowed number of loops.
directive.foreach.max_loops = -1

#include - Renders local file(s) that are not parsed by Velocity

Format:

# [ { ] include [ } ] ( arg [ arg2 ... argn ] )

Usage:

  • arg - Refers to a valid file under TEMPLATE_ROOT.

Examples:

  • String: #include( "disclaimer.txt" "opinion.txt" )+
  • Variable: #include( $foo $bar )

#parse - Renders a local template that is parsed by Velocity

Format:

# [ { ] parse [ } ] ( arg )

Usage:

  • arg - Refers to a template under TEMPLATE_ROOT.

Examples:

  • String: #parse( "lecorbusier.vm" )
  • Variable: #parse( $foo )

Recursion permitted. See directive.parse.max_depth in velocity.properties to change from parse depth. (The default parse depth is 10.)

#stop - Stops the template engine

Format:

# [ { ] stop [ } ]

Usage:

This will stop execution of the current template. This is good for debugging a template.

#break - Stops the current directive

Format:

# [ { ] break [ } ]

Usage:

This will break execution of the current content directive. This is good for exiting a #foreach loop early, but also works in other scopes. You can even pass the scope control reference for a specific outer scope to break execution of all scopes outward to the specified one.

#evaluate - Dynamically evaluates a string or reference

Format:

# [ { ] evaluate [ } ] ( arg )

Usage:

  • arg - String literal or reference to be dynamically evaluated.

Examples:

  • String: #evaluate( 'string with VTL #if(true)will be displayed#end' )
  • Variable: #evaluate( $foo )

#define - Assigns a block of VTL to a reference

Format:

# [ { ] define [ } ] ( $ref ) statement # [ { ] end [ } ]

Usage:

  • $ref - Reference that is assigned the VTL block as a value.
  • statement - Statement that is assigned to the reference.

Example:

  • #define( $hello ) Hello $who #end #set( $who = "World!") $hello ## displays Hello World!

#macro - Allows users to define a Velocimacro (VM), a repeated segment of a VTL template, as required

Format:

# [ { ] macro [ } ] ( vmname $arg1 [ = def1 ] [ $arg2 [ = def2 ] $arg3 [ = def3 ] ... $argn [ = defn ] ] ) [ VTL code ] # [ { ] end [ } ]

Usage:

  • vmname - Name used to call the VM (#vmname)
  • $arg1 $arg2 ... - Arguments to the VM. There can be any number of arguments, but the number used at invocation must match the number specified in the definition, unless there is a default value provided for missing parameters.
  • def1, def2, ... - Optional default values provided for macro arguments. If a default value is provided for an argument, a default value must also be provided to all subsequent arguments.
  • VTL code - Any valid VTL code, anything you can put into a template, can be put into a VM.

Once defined, the VM is used like any other VTL directive in a template.

#vmname( $arg1 $arg2 )

Except, that when you wish to call a VM with a body, then you must prefix the name of the VM with @. The content of that body may be referenced in the macro definition via $!bodyContent as many or few times as you like.

#@vmname( $arg1 $arg2 ) here is the body#end

VMs can be defined in one of two places:

  1. Template library: can be either VMs pre-packaged with Velocity or custom-made, user-defined, site-specific VMs; available from any template
  2. Inline: found in regular templates, only usable when velocimacro.permissions.allowInline=true in velocity.properties.

Since 2.0, when a macro argument is null or invalid, its rendering will display its local name. The following block of code:

#macro( vmname $foo ) $foo #end
#vmname( $null )

will display $foo. If you wish to revert to the 1.x behavior (which is to display $null), you can set the velocimacro.preserve.arguments.literals configuration property to true (since 2.1).

Comments

Comments are not rendered at runtime.

Single Line Comments

Example:

## This is a comment.**

Multi Line Comments

Example:

#*
  This is a multiline comment.
  This is the second line.
*#

Unparsed Content

Unparsed content is rendered at runtime, but is not parsed or interpreted.

Example:

#[[

This has invalid syntax that would normally need 
"poor man's escaping" like:

 - #define()
 - ${blah

]]#