$null check in velocity
Asked Answered
O

3

58

I came to know about null check using $null in velocity 1.6 through a resource updated by you. Resource: Reading model objects mapped in Velocity Templates But I am facing so many challenges that there is no $null for null check in velocity as there is no documentation provided about this. Please provide me with documentation stating $null as valid for null check in velocity.

Ochoa answered 13/8, 2010 at 16:1 Comment(0)
S
116

To check if a variable is not null simply use #if ($variable)

#if ($variable) 
 ... do stuff here if the variable is not null
#end

If you need to do stuff if the variable is null simply negate the test

#if (!$variable)
 ... do stuff here if the variable is null
#end
Spitter answered 13/8, 2010 at 16:9 Comment(2)
this would also return true in case of boolean values. This is a nice documentation for null checks : wiki.apache.org/velocity/CheckingForNullConners
following up on @TJ comment, any idea how to import NullTool as of recent? It does not appear to be in velocity-tools 2.0.N
M
4

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 )

Note: The conditional will also pass if the result of $car.fuel is the boolean false. What this approach is actually checking is whether the reference is null or false.

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" == "" )

Note: The conditional will also pass if the result of $car.fuel is an empty String. 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: Combine Approach 1 and 2. This will check for null and null only.

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

Note: The logic underlying here is that: "(null or false) and (null or

empty-string)" => if true, must be null. This is true because "false and empty-string and not null" is never true. IMHO, this makes the template too complicated to read.

Manganese answered 18/5, 2021 at 13:1 Comment(2)
If you're using velocity for AWS API Gateway, you need #if($car.fuel == "") to check for null in the response. The implicit approach (#if($car.fuel)) will not work.Durian
This is an interesting answer, but it looks like a direct copy paste from cwiki.apache.org/confluence/display/VELOCITY/CheckingForNullAccumulate
P
0

For a variable with a boolean value, this might do the trick:

#if ($variable || $variable == "false")
  ... if the boolean $variable is not null
#else
  ... if the boolean $variable is null
#end
Phasia answered 2/7 at 5:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.