How to check if a value is null with Velocity

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.


References:

Velocity

Recent Comments