How to include a velocity template in a template

The command #parse is used to include a velocity tempalte in a template. The context of the first template is passed to the sub template.

Example in java :

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 VelocitySimple2 {

	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( "example2.vm" );

        // Create the 
        VelocityContext context = new VelocityContext();
        context.put("name", "World");

        try {
	        // Create the output file
	        Writer out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream( new File( sourceDirectory + "example2.txt" ) ), "UTF8") );
	    	
	        t.merge( context, out);
	        
	        out.close();
        } catch ( Exception e ){
        	e.printStackTrace();
        }
	}
	
}



Create the following template called example2.vm:


Hello $name!
#parse("example2include.vm")	

Create the following subtemplate called example2include.vm:


Your name is $name.
	

The generated file example.txt will be:

	
Hello World!
Your name is World.
	

The code first initilize the VelocityEngine using the file resource loader. It set the loader path to the directory contening the templates. Then it gets a template from the template directory using the getTemplate method. A set of variables is set in the VelocityContext, here it's name = World, that context is then passed to the merger method that generate the output files. The variables defined as $name as replaced in the template.


References:

Velocity

Recent Comments