37

I often have cases when a string value is absent and/or empty. Is this the best way to test this condition?

#if( $incentive.disclaimer && $!incentive.disclaimer != '' ) 
   $incentive.disclaimer 
#end
rsturim
  • 6,756
  • 15
  • 47
  • 59
  • Dave, what too would you suggest? – Andy Dingfelder Apr 18 '13 at 02:54
  • Don't use Quiet Reference Notation $!incentive.disclaimer inside #if. It doesn't give you anything there. But you might sometimes want logical NOT !$incentive.disclaimer (not the same thing!). – DenisS Feb 14 '14 at 13:52

3 Answers3

45

If you just want Velocity to display the value if there, or display nothing if absent, a quiet reference by itself will do the trick:

$!incentive.disclaimer

If you're wanting to explicitly test for empty, StringUtils from Apache Commons Lang can help. First add it to your Context (reference here):

context.put("StringUtils", StringUtils.class);

Though if you're on an older version of Velocity, it may not like the class reference, so you can add an instance instead:

context.put("StringUtils", new StringUtils());

Then you can call its isEmpty method from your Velocity template:

#if($StringUtils.isEmpty($incentive.disclaimer))
    ## logic here...
#end

If you want whitespace treated as empty, there's also isBlank.

Evan Haas
  • 2,524
  • 2
  • 22
  • 34
  • 4
    @Vadzim's answer does the job without adding an additional third party library – Adriano Oct 02 '13 at 17:12
  • 1
    @Adrien Be But it makes the code kinda obscure (and it was given one month later) while this one is extremely readable. I prefer this one because of that and because this one indirectly illustrates that one can pass any class or instance into the context for use in the template (it doesn't necessarily need to be an additional third party library). – SantiBailors Aug 28 '14 at 11:51
44

For cases where just $!incentive.disclaimer doesn't fit http://wiki.apache.org/velocity/CheckingForNull suggests a short solution:

#if( "$!car.fuel" != "" )
Vadzim
  • 24,954
  • 11
  • 143
  • 151
16

You want Quiet Reference Notation: $!incentive.disclaimer

Bla bla $!incentive.disclaimer. 

If $incentive.disclaimer is null or "", Velocity will render:

Bla bla .

Refer to the official Guide section: https://velocity.apache.org/engine/devel/user-guide.html#quiet-reference-notation

Sometimes you do need #if

Most common case when you do want #if: your variable is just a part of a bigger piece of text and you don't want to show it if the variable is empty. Then you need this:

#if($incentive.disclaimer && !$incentive.disclaimer.empty) 
    Please read our incentive disclaimer:
    $incentive.disclaimer
#end
Community
  • 1
  • 1
DenisS
  • 1,637
  • 19
  • 15