Q: I want to check for null, something like this:

#if ($car.fuel == null)

A: There are several approaches. Select the one most suitable depending on what you really want to do. (Thanks, everybody, for all the feedback on the user list.) See also: Bugzilla #20999, Bugzilla #27741, VelocityNullSupport.

Approach 1: Use the fact that null is evaluated as a false conditional. (cf. http://velocity.apache.org/engine/devel/user-guide.html#Conditionals)

#if( ! $car.fuel )

Approach 2: Use the fact that null is evaluated as an empty string in quiet references. (cf. http://velocity.apache.org/engine/devel/user-guide.html#quietreferencenotation)

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

BTW, just checking for empty can be achieved by:

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

Approach 3: Combine Approach 1 and 2. This will check for null and null only.

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

Approach 4: Use a Tool that can check for null (NullTool,ViewNullTool).

#if( $null.isNull($car.fuel) )

Approach 5: Don't check for null directly, use a self-explaining method.

#if( $car.fuelEmpty )

public boolean isFuelEmpty()
  // return true if fuel is empty.

Approach 6: Use a custom directive. cf. IfNullDirective, IfNotNullDirective

#ifnull( $car.fuel )
#ifnotnull( $car.fuel )

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

CheckingForNull (last edited 2012-12-11 14:51:05 by 195)