Velocity Templates and Newlines

If you're reading this article you've probably encounted the same problem as I have. I was trying to put a newline '\n' character in the value of a variable in a Velocity template.

Attempt 1:

I assumed \n would work...

CODE:
  1. #if ( !$foo )
  2.   #set ( $foo = "There was no foo set in the Context.\nPlease do something about it." )
  3. #end

This produced There was no foo set in the Context.\nPlease do something about it. as the value of $foo.

Attempt 2:

I just thought this was worth a shot :D

CODE:
  1. #if ( !$foo )
  2.   #set ( $foo = "There was no foo set in the Context.
  3. Please do something about it." )
  4. #end

And the template failed to compile

Solution:

Basically, the easiest way I found is to place the newline, carriage return or other special character in the context.

JAVA:
  1. public Template handleRequest( HttpServletRequest request, HttpServletResponse response, Context context )
  2. {
  3.     ...
  4.  
  5.     context.put( "nl", "\n" );
  6.     context.put( "cr", "\r" );
  7.  
  8.     ...
  9. }

And in your template:

CODE:
  1. #if ( !$foo )
  2.   #set ( $foo = "There was no foo set in the Context.${nl}Please do something about it." )
  3. #end

Maybe not the best solution but it works for me. If you expect to use it across your entire application I suggest you override VelocityServlet.createContext in your Servlet to add these characters to every context in your application.

Example:

JAVA:
  1. protected Context createContext( HttpServletRequest request, HttpServletResponse response ) {
  2.     Context context = super.createContext( request, response );
  3.    
  4.     context.put( "nl", "\n" );
  5.     context.put( "cr", "\r" );
  6.    
  7.     return context;
  8. }

No Comments so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required, but not displayed publically)