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

本小妞迷上赌 提交于 2019-11-27 17:12:33

问题


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

回答1:


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.




回答2:


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

#if( "$!car.fuel" != "" )



回答3:


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


来源:https://stackoverflow.com/questions/13158441/velocity-whats-the-most-efficient-way-to-check-if-a-string-is-empty-and-not-nu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!