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. Consider the following
piece of code:
#if( $display ) <strong>Velocity!</strong> #end
The variable $display
is evaluated to determine
whether it is true, which will happen under one of two
circumstances:
$foo
is a
java.lang.Boolean
object (True/False) which has
a true value.
The value is not null.
The Velocity context only contains Java objects, so any
method that returns a boolean primitive will automatically wrapped into
a java.lang.Boolean
object.
The content between the #if
and the
#end
statements becomes the output if the evaluation
is true. In this case, if $foo
is true, the output
will be: Velocity!
. Conversely, if
$foo
has a null value, or if it is a boolean false,
the statement evaluates as false, and there is no output.
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:
Example 5.4. Using #if/#elseif/#else to select multiple template pieces
#set ($direction = 15) #set ($wind = 6) #if( $direction < 10 ) <strong>Go North</strong> #elseif( $direction == 10 ) <strong>Go East</strong> #elseif( $wind == 6 ) <strong>Go South</strong> #else <strong>Go West</strong> #end
In this example, $direction
is greater than 10,
so the first two comparisons fail. Next $wind
is
compared to 6, which is true, so the output is Go
South
.
When you wish to include text immediately following a
#else
directive you need to use curly brackets
immediately surrounding the directive to differentiate it from the
following text:
#if( $foo == $bar)it's true!#{else}it's not!#end</li>