Search code examples
javavelocityvelocity-tools

Unable to set Nulll in Velocity Template


I am trying to set a variable to null in Velocity. I am trying:

#set ($acessSpeed = null)

I was reading the velocity null support wiki. It says we can set a value to null this way. https://wiki.apache.org/velocity/VelocityNullSupport

But when i try it I get an error saying "Encountered "null" at ...."

The problem i am having i have a huge template with multiple if blocks, which get executed if the condition is satisfied. So at the end of each if block i need to set the value of accessSpeed to null.

#if (some condition)
     access speed value set here.
.
.
.
#end
// I need to set the access speed value to null here.
#if (some other condition)
    access speed value to be set to something again.
.
.
.
#end

I can use different variable for each if block but i was wondering if there was a simpler way to do it.

Any suggestions would be helpful.


Solution

  • It depends upon your configuration. To do what you need, you need to configure Velocity with:

    directive.set.null.allowed = true
    

    Then, you can set your variable to null with:

    #set($foo = $null)
    

    where $null is just an undefined variable.

    Otherwise, if the only purpose is to test the variable, then a convenient trick is to set its value to false.

    #set($foo = false)
    #if($foo) this will be displayed #end