How to print a value in a Velocity template

The velocity template access the values defined in the context using the $ character, the output is printed in the result.

Create the following template called example_value.vm:

Hello $name!

This is a test


This example loads the VelocityEngine and initializes the engine. Then it loads the template by accessing it using the template file. The VelocityContext is created, the property name is added with the value Olivier. The output file writer is created and the template merges the context in the output file. The writer is closed to ensure the file is closed on the filesystem. If any error happens they are written in system err.

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

        // Create the context and add the properties
        VelocityContext context = new VelocityContext();
        context.put("name", "Olivier");

        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:

	
Hello Olivier!

This is a test
	

The merged text is written in the output file. In this example Hello Olivier! is written in the output. The template value $name was merged with the value name from the VelocityContext passed when the template was merged. The input is encoded in utf-8, this way all the utf-8 characters can be passed in the context and merged with the template.


References:

Velocity

Share this article:

Recent Comments