Unsetting a variable in Velocity
Question
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.
Solution
Read on...
Depending on how Velocity is configured, it is usually not possible to remove an existing reference from the context via this mechanism. (Note that this can be permitted by changing one of the Velocity configuration properties)
In the VE default configuration has property
directive.set.null.allowed = false
if true, having a right hand side of a #set() statement with an invalid reference or null value will set the left hand side to null. If false, the left hand side will stay the same
Change it to true
using setProperty()
on org.apache.velocity.app.Velocity
and you're ready to go.
OTHER TIPS
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
If you are trying to get scoped variables, you can abuse the scope established by #foreach
:
#foreach($localVar in [ 'theValue'])
#end
## localVar will be unset (or returned to previous value) again