2015年6月30日星期二

velocity如何判空

问题: I want to check for null, something like this:
#if ($car.fuel == null)

Approach 1: null在条件表达式中表示false. (null is evaluated as a false conditional.)
#if( ! $car.fuel )
  • 备注: 如果$car.fuel为'false',依然可以通过判断.What this approach is actually checking is whether the reference is null or false.
Approach 2: null是一个空string (null is evaluated as an empty string in quiet references.)
#if( "$!car.fuel" == "" )
  • 备注: 当$car.fuel为空String ''依然可以通过pass. What this approach is actually checking is whether the reference is null or empty.
BTW, just checking for empty can be achieved by:
#if( "$car.fuel" == "" )
Approach 3: 结合Approach 1 and 2,就可以判断null并且只判断null.
#if ((! $car.fuel) && ("$!car.fuel" == ""))

Approach 4: Use a Tool that can check for null (NullTool,ViewNullTool).
#if( $null.isNull($car.fuel) )
  • Note: Of course, NullTool must be in the Context as $null in this case.
Approach 5: Don't check for null directly, use a self-explaining method.
#if( $car.fuelEmpty )
  • Note: 建议的方法. You have to implement the method, but it makes the template so easy-to-read.
public boolean isFuelEmpty()
{
  // return true if fuel is empty.
}
Approach 6: Use a custom directive. cf. IfNullDirectiveIfNotNullDirective
#ifnull( $car.fuel )
#ifnotnull( $car.fuel )
  • Note: You will have to register the directive in your velocity.properties.

userdirective = org.apache.velocity.tools.generic.directive.Ifnull
userdirective = org.apache.velocity.tools.generic.directive.Ifnotnull

没有评论:

发表评论