33

In velocity I have a variable which its value is null. I don't want to display anything in that case.

Currently the template engine translates "" to null so I have to do.

#set ( $a = "")
#if ($a) 
   assert("never prints a neither gets here: " + $a)
#end

Is there a way I could do that directly? I'd like to be able to make something like:

This is the variable $a. ## in case that $a is null i don't want 'dollar a' to be displayed
Jordi P.S.
  • 3,838
  • 7
  • 36
  • 59
  • 6
    You might find the following Velocity wiki page interesting: [Checking for null](http://wiki.apache.org/velocity/CheckingForNull). Also check out [$null check in velocity](http://stackoverflow.com/q/3478638/851811) – Xavi López Sep 04 '12 at 12:46

3 Answers3

57

$!a does the trick. You can use this form directly without an if check.

simhumileco
  • 31,877
  • 16
  • 137
  • 115
Irmak Cakmak
  • 1,343
  • 11
  • 11
26

You want Quiet Reference Notation: $!a

Here's your example:

This is the variable $!a.

If $a is null or "", Velocity will render:

This is the variable .

Official Guide section: https://velocity.apache.org/engine/devel/user-guide.html#quietreferencenotation

simhumileco
  • 31,877
  • 16
  • 137
  • 115
DenisS
  • 1,637
  • 19
  • 15
1

Another alternative is to modify your if statement per Checking for Null (thanks for the link @xavi-lópez):

Approach 2: Use the fact that null is evaluated as an empty string in quiet references. (cf. http://velocity.apache.org/engine/devel/user-guide.html#quietreferencenotation)

So, your code would be:

#set ( $a = "")
#if ("$a" != "") 
   assert("never prints a neither gets here: " + $a)
#end
cameck
  • 2,058
  • 20
  • 32