我经常遇到字符串值不存在和/或为空的情况.这是测试这种情况的最佳方法吗?
#if( $incentive.disclaimer && $!incentive.disclaimer != '' )
$incentive.disclaimer
#end
Run Code Online (Sandbox Code Playgroud)
Eva*_*aas 37
如果你只是希望Velocity在那里显示值,或者如果没有则显示任何内容,那么一个安静的引用本身就可以解决问题:
$!incentive.disclaimer
Run Code Online (Sandbox Code Playgroud)
如果你想显式测试为空,那么来自Apache Commons Lang的StringUtils可以提供帮助.首先将它添加到您的Context(在此引用):
context.put("StringUtils", StringUtils.class);
Run Code Online (Sandbox Code Playgroud)
虽然如果您使用的是较旧版本的Velocity,它可能不喜欢类引用,因此您可以添加实例:
context.put("StringUtils", new StringUtils());
Run Code Online (Sandbox Code Playgroud)
然后,您可以从Velocity模板中调用其isEmpty方法:
#if($StringUtils.isEmpty($incentive.disclaimer))
## logic here...
#end
Run Code Online (Sandbox Code Playgroud)
如果你想要将空格视为空,那么还有isBlank.
Vad*_*zim 33
对于$!incentive.disclaimer不适合的情况http://wiki.apache.org/velocity/CheckingForNull建议一个简短的解决方案:
#if( "$!car.fuel" != "" )
Run Code Online (Sandbox Code Playgroud)
Den*_*isS 15
Bla bla $!incentive.disclaimer.
Run Code Online (Sandbox Code Playgroud)
如果$ incentive.disclaimer为null或"",Velocity将呈现:
Bla bla .
Run Code Online (Sandbox Code Playgroud)
请参阅官方指南部分:https: //velocity.apache.org/engine/devel/user-guide.html#quiet-reference-notation
最常见的情况是你想要#if:你的变量只是一个较大文本的一部分而你不想在变量为空时显示它.然后你需要这个:
#if($incentive.disclaimer && !$incentive.disclaimer.empty)
Please read our incentive disclaimer:
$incentive.disclaimer
#end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56006 次 |
| 最近记录: |