Velocity nulls和空字符串

时间:2012-09-04 12:30:10

标签: java templates velocity

在速度中,我有一个变量,其值为 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

3 个答案:

答案 0 :(得分:43)

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

答案 1 :(得分:17)

您需要安静的参考符号:$!a

以下是您的示例:

This is the variable $!a.

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

This is the variable .

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

答案 2 :(得分:0)

另一种替代方法是根据 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