How to iterate a list using a Velocity template

A Velocity Template can iterate a list using a foreach loop on the elements.

Create the following template called example_list.vm:

I like the following fruits:

#foreach( $fruit in $fruits )
    $fruit
#end


This example creates a velocity template that iterates on the fruits variable. The fruits variable is created in the java code calling the template, it is passed using the context and the fruits name. The VelocityEngine is create first. It's possible to check an interval for reloading the files, this prevents from reloading the full configuration. After the VelocityEngine is initialized, the template is loaded from the file. Then the context is created with the variable passed for rendering. The output file is created and merged with the context. Once that is done, the output file is closed.

Create the following java file:

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

    public static void main(String[] argv){
	
	// Source directory
	String sourceDirectory = "V:/tmp/velocity/";
		
	// Source directory
        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 file
        Template t = ve.getTemplate( "example_list.vm" );

        // Create the context and add the properties
        VelocityContext context = new VelocityContext();
        List<String> fruits = Arrays.asList( "apple", "oranges", "pears");
        context.put("fruits", fruits);

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

}


The output will be:

	
I like the following fruits:

	apple
	oranges
	pears
	

The generated file contains the description String and one fruit per line. We have 3 fruits in input so 3 lines in output.


References:

Velocity

Recent Comments