3. Language elements

Like other formal languages, Velocity consists of a number of elements:

Each of these elements will be introduced in this chapter.

3.1 Statements and Directives

Velocity directives are language elements than allow the template designer to manipulate the rendering of the template. A directive is part of a Velocity statement:

#set($a = 10)           ## Velocity single-line statement
^\_/\_______/
| |     |
| |     +---------- expression in brackets 
| |
| +---------------- Velocity directive
|
+------------------ begin of Velocity statement



+------------------ begin of Velocity statement
|
|   +-------------- Velocity directive
|   |
|   |          +--- expression in brackets
| __|__  ______|______
v/     \/             \
#foreach($i in [0..10])   ## Velocity multi-line statement
  Counter is $i           ## statement body
#end                      ## end of Velocity multi-line statement

Velocity knows about single-line and multi-line statements. A single-line statement starts with a single # character, followed by directive itself. Some directives also take parameters in brackets. A single-line statement then ends immediately.

Example 3.1. Velocity single-line statements

#set($name = "apple")

#include("header.html")

#parse("header.vm")

#stop

A multi-line statement starts like a single-line statement, but also has a statement body. This body ends with #end.[1]

Example 3.2. Velocity multi-line statements

#foreach($i in [1..10])
  The count is $i
#end

#literal
 This is a literal block of text
#end

#if ($fruit == "apple")
  This is an apple.
#else
  This is not an apple.
#end

[Note]Note

The #if/#else/#end combo is a special case because it might contain multiple statement bodies between its elements.

If you need to explicitly separate a Velocity directive from surrounding text, it is possible to wrap it in curly braces ({ and }):

#{set}($name = "apple")

#{foreach}($i in [1..10])
 The count is $i
#{end}

All available Velocity directives are listed in the Directives chapter.

[Note]Note

While the hash sign is technically not part of the directive, we will still speak about the #if or #set directive in the latter chapters.



[1] Technically speaking, the opening statement and #end can be on the same line. We will still call it a multi-line statement.