How to escape a # character in Velocity

Velocity doesn't parse text that is between #[[ and ]]#, so the character # can be added to the template between them.

Syntax:

#[[#]]# 

Example:

The following example creates a template with the char # escaped with #[[ and ]]#.

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

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

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

Create the following template called example5.vm:


Hello #[[#]]# $name 


The output will be:

Hello # Olivier 

References:

Java 8
Online tool generating MD5
Raimbow table to revert MD5