3

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.

hell_storm2004
  • 1,401
  • 2
  • 33
  • 66

1 Answers1

7

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
Claude Brisson
  • 4,085
  • 1
  • 22
  • 30
  • @Calude Brisson Thanks for the info. Do i put that directive statement at the start of the template? – hell_storm2004 Apr 09 '17 at 01:44
  • No, it is a configuration value that belongs to the `velocity.properties` file. Alternatively, you can set it up pro grammatically using `setProperty()` on the Velocity or RuntimeInstance you are using, *before* initialization. – Claude Brisson Apr 09 '17 at 07:24
  • That was a pretty dumb question. I should have looked it up! Thanks for the help. – hell_storm2004 Apr 10 '17 at 13:32