Stu Thompson
Stu Thompson

Reputation: 38868

How do I create a velocity template that outputs two '#' litterals at the beginning of the line?

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?

Upvotes: 3

Views: 1487

Answers (4)

Stu Thompson
Stu Thompson

Reputation: 38868

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.)

Upvotes: 3

Simon Nickerson
Simon Nickerson

Reputation: 43159

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

Upvotes: 3

cadrian
cadrian

Reputation: 7376

Use the Velocity context:

${esc.h}${esc.h}

Upvotes: 4

Aaron Maenpaa
Aaron Maenpaa

Reputation: 122850

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

## This is a comment

Upvotes: -1

Related Questions