Unsetting a variable in Velocity

Simon Nickerson picture Simon Nickerson · Mar 18, 2009 · Viewed 14.9k times · Source

Is it possible to set a Velocity reference to 'null' or 'undefined'?

The Velocity template language reference says

#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 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. (emphasis mine)

I cannot find an equivalent #unset macro.

Answer

Merzbow picture Merzbow · Mar 18, 2009

You can set the reference to false. As a non null reference is considered true, you can then test if the reference is set. This is useful in loops.

#foreach ($obj in $list)
#set ($x = false)
#set ($x = $obj.maybeNull())
#if ($x)
...
$x
#end
#end