Velocity, what's the most efficient way to check if a string is empty and not null

rsturim picture rsturim · Oct 31, 2012 · Viewed 61.7k times · Source

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

Answer

Evan Haas picture Evan Haas · Oct 31, 2012

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.