views:

44

answers:

2

How do you append a newline in velocity template using set? This does not work.

#(set $some = "$a \n $b")

Prints literally \n.

Doing this also does not work :

VelocityContext context = new VelocityContext();
context.put("esc", new EscapeTool());
Velocity.evaluate(context, writer, "LOG", template);
+2  A: 

You can use $esc.n or its synonym $esc.newline from the EscapeTool for this:

#set($some = $a + $esc.n + $b)

How to init tools:

ToolManager velocityToolManager = new ToolManager();
velocityToolManager.configure("velocity-tools.xml");
VelocityContext context = new VelocityContext(velocityToolManager.createContext());

You can get default velocity-tools.xml from here (it's also included into tools jar) and enable tools that you need.

serg
@serg - Thanks. How do I add `EscapeTool` to context? I did `context.put("esc", new EscapeTool())`. It did not work. This is not a web app, just a plain java code with velocity macro.
fastcodejava
@fastcodejava I added it to the answer.
serg
@serg - I am doing the code as above, why doesn't that work?
fastcodejava
@fastcodejava What exactly doesn't work?
serg
@serg - Code snippet I posted above doesn't work.
fastcodejava
@fastcodejava because it is not the right way to initialize tools. Why not just use what I posted in the answer?
serg
Why doesn't velocity have \n?
javaguy
+1  A: 

You know, in modern versions of Velocity you just put the line break in.

#set( $haslinebreak = "this has
a line break" )
Nathan Bubna