Velocity nulls和空字符串

在速度我有一个变量,其值为null 。 在这种情况下我不想显示任何内容。

目前模板引擎将“”转换为null,所以我必须这样做。

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

有没有办法直接做到这一点? 我希望能够做出像:

 This is the variable $a. ## in case that $a is null i don't want 'dollar a' to be displayed 

$!a诀窍。 您可以直接使用此表单而无需检查。

你想要安静的参考符号:$!a

这是你的例子:

 This is the variable $!a. 

如果$ a为null或“”,则Velocity将呈现:

 This is the variable . 

官方指南部分: https : //velocity.apache.org/engine/devel/user-guide.html#quietreferencenotation

另一种方法是修改每个Checking for Null的 if语句(感谢链接@ xavi-lópez):

方法2:使用在安静引用中将null评估为空字符串的事实。 (参见http://velocity.apache.org/engine/devel/user-guide.html#quietreferencenotation )

所以,你的代码将是:

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