tags:

views:

420

answers:

4

I need to create a velocity document that has some lines prefixed with ¨## Foo", but since the # is the velocity directive command, it is not working for me.

What I want my output document to look like:

## Foo this
## Bar that
k1, v1
k2, v2
k3, v3

Escaping has not worked out how I expected. The below does not work, obviously, as the #s are un-escaped):

## Foo this
## Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end

The ## lines don't show up--again, as expected. But, my attempts at escaping do not work either. Escaping solution one:

\## Foo this
\## Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end

or this, escaping solution two:

\#\# Foo this
\#\# Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end

or even this...

# set($msg = "##") 
$msg Foo this
$msg Bar that
#foreach( $foo in $bar )
$foo.key, $foo.value
#end

This last one really confused me.

Any ideas?

A: 

"##" is the single line comment delimiter in VTL, which is probably the start of your problems.

## This is a comment
Aaron Maenpaa
Obviously, and why I state as much in the question.
Stu Thompson
+3  A: 

Use the Velocity context:

${esc.h}${esc.h}
cadrian
+3  A: 

If you don't want to add org.apache.velocity.tools.generic.EscapeTool or similar to your context, you can use a slightly modified version of your third try:

#set($msg = "#") 
${msg}${msg} Foo this
Simon Nickerson
This works, and doesn't require messing with the context (which would require a code changes on my part.) Fantastic. I don't understand why "##" doesn't work, but this 2x "#" does. :P But, I'm not complaining...it works!
Stu Thompson
I assume that when Velocity parses the template, comments are extracted before anything else. So everything after the double hash in the template would disappear entirely. But I'm just guessing.
Simon Nickerson
+2  A: 

Sigh....There is a difference between single quote and double quotes. This works as expected:

#set($msg = '##') 
$msg Foo this

Which prints out exactly what I wanted:

## Foo this

From the Velocity Users Guide:

Single quotes will ensure that the quoted value will be assigned to the reference as is. Double quotes allow you to use velocity references and directives to interpolate, such as "Hello $name"

(I'm still stumped as to why \#\# does not work.)

Stu Thompson