Oct
29
2003
Velocity whitespace handling is not as written
Posted by: Kevin Dangoor in Software DevelopmentIn the Velocity User Guide, it says that “Velocity’s behaviour is to gobble up excess whitespace.” and gives some examples that it says will produce the same output. That’s not the way it works for me:
public void testVelocityWhitespace()
{
VelocityEngine ve = new VelocityEngine();
try
{
ve.init();
VelocityContext context = new VelocityContext();
String test1 = "Send me #set($foo = ["$10 and ","a cake"])#foreach($a in $foo)$a #end please.";
String test2 = "Send me\n" +
"#set( $foo = ["$10 and ","a cake"] )\n" +
"#foreach( $a in $foo )\n" +
"$a\n" +
"#end\n" +
"please.";
String test3 = "Send me\n" +
" #set($foo = ["$10 and ","a cake"])\n"
" #foreach ($a in $foo )$a\n" +
" #end please.";
StringWriter sw = new StringWriter();
ve.evaluate(context, sw, "test", test1);
String output1 = sw.toString();
sw = new StringWriter();
ve.evaluate(context, sw, "test", test2);
String output2 = sw.toString();
sw = new StringWriter();
ve.evaluate(context, sw, "test", test3);
String output3 = sw.toString();
System.out.println(output1);
System.out.println(output2);
System.out.println(output3);
assertEquals(output1, output2);
assertEquals(output1, output3);
}
catch (Exception e)
{
e.printStackTrace();
fail("Template didn't work correctly.");
}
}
Perhaps there’s a property that controls it. Either way, the documentation should probably change to reflect what Velocity really does. (By the way, this is not at all a knock on Velocity. I think it’s a very nice templating system.)
Entries (RSS)
February 6th, 2005 at 6:33 pm
BEWARE OF DRAGONS!
As an ugly hack you can use the Velocity line comment syntax “##” to workaround this whitespace problem.
The whitespace after #if seems to be ignored so you can write constructs like this:
#macro( testMacro )
#if ( )
This output will not have any leading whitespace, nor trailing whitespace. Because the line is terminated via the line comment##
#else
Without the line comment, this line has an extra new line which wrecks your template.
#end
#end
Enjoy
August 8th, 2008 at 2:41 pm
Wow, after 5 years the document still read like this. Thank god for this page, as the newline was screwing things up for me!