Unsetting a variable in Velocity
Solution 1
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.
Solution 2
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
Solution 3
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
fmunshi
I am a software engineer working at Google UK in London. All original source snippets I post on stackoverflow are dedicated to the public domain. Do with them as you see fit.
Updated on June 12, 2022Comments
-
fmunshi about 2 years
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. -
Lama almost 9 yearsSince velocity variables will keep the old value, if you try to assign a "null-value", I found this solution quite nice. At the end of the loop I just set the variable to false and when you cannot assign a value it's value will be false.