Java velocity if null
The #if directive in Velocity allows for text to be included when the web page is generated, on the conditional that the if-statement is true. Consider the following piece of code:
#if( $display ) Velocity! #end
The variable $display is evaluated to determine whether it is true, which will happen under one of two circumstances:
- $foo is a java.lang.Boolean object (True/False) which has a true value.
- The value is not null.
The Velocity context only contains Java objects, so any method that returns a boolean primitive will automatically wrapped into a java.lang.Boolean object.
The content between the #if and the #end statements becomes the output if the evaluation is true. In this case, if $foo is true, the output will be: Velocity! . Conversely, if $foo has a null value, or if it is a boolean false, the statement evaluates as false, and there is no output.
An #elseif or #else element can be used with an #if element. Note that the Velocity Templating Engine will stop at the first expression that is found to be true:
Example 5.4. Using #if/#elseif/#else to select multiple template pieces
#set ($direction = 15) #set ($wind = 6) #if( $direction < 10 ) Go North #elseif( $direction == 10 ) Go East #elseif( $wind == 6 ) Go South #else Go West #end
In this example, $direction is greater than 10, so the first two comparisons fail. Next $wind is compared to 6, which is true, so the output is Go South .
When you wish to include text immediately following a #else directive you need to use curly brackets immediately surrounding the directive to differentiate it from the following text:
CheckingForNull
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)
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)
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:
Approach 3: Combine Approach 1 and 2. This will check for null and null only.
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.
Approach 4: Use a Tool that can check for null (NullTool,ViewNullTool).
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.
Note: This is my (Shinobu Kawai’s) recommended solution. 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. IfNullDirective, IfNotNullDirective
#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
Java velocity if null
The value null is tested as the boolean value false by Velocity
Create the following template called example4.vm:
This is a test #if( !$test ) Test is null #end #if( $test == true ) Test is NOT null #end
Create the following java file:
import static org.junit.Assert.assertEquals; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; public class VelocitySimple4 < public static void main(String[] argv)< // Source directory String sourceDirectory = "V:/tmp/velocity/"; // Create the velocity engine VelocityEngine ve = new VelocityEngine(); ve.setProperty( "resource.loader", "file"); ve.setProperty( "file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); ve.setProperty( "file.resource.loader.path", sourceDirectory); ve.setProperty( "file.resource.loader.cache", true); ve.setProperty( "file.resource.loader.modificationCheckInterval", "2"); ve.init(); // Get the template Template t = ve.getTemplate( "example4.vm" ); // Create the VelocityContext context = new VelocityContext(); context.put("test", null); try < // Create the output file Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( new File( sourceDirectory + "example4.txt" ) ), "UTF8") ); t.merge( context, out); out.close(); >catch ( Exception e ) < e.printStackTrace(); >> >
The generated file example4.txt will be:
This is a test Test is null
The code first initilize the VelocityEngine using the file resource loader. The validable test is set in the context with the value null, then the template is merged with the context and the output is stored in the example4.txt file.