Stand with Ukraine 🇺🇦
Products
Services
Blog
About Us

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

The variable $foo is evaluated to determine whether it is true, which will happen under one of those circumstances:

  • $foo is a boolean (true/false) which has a true value

  • $foo is a string or a collection which is not null and not empty

  • $foo is a number which is not equal to zero

  • $foo is an object (other than a string, a number or a collection) which is not null (and for which the standard public methods for querying the object size, length or boolean/string representations, if they exist, indicate a non-empty, non-zero, non-false object).

#set($foo = true)

#if($foo)
   <strong>Hello from if</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. In the following example, suppose that $foo has a value of 15 and $bar has a value of 6.

#set($foo = 15)
#set($bar = 6)

#if( $foo < 10 )
    **Go North**
#elseif( $foo == 10 )
    **Go East**
#elseif( $bar == 6 )
    **Go South**
#else
    **Go West**
#end