59

I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well

This:

\#\#

prints:

\#\#

I would like:

## 
Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179
  • 4
    Note that as of 2012 at least, you can now escape things in Velocity with backslash: \# and \$. See http://velocity.apache.org/engine/devel/user-guide.html#Getting_literal – Steven Feb 17 '12 at 18:06
  • 2
    see also http://velocity.apache.org/engine/1.7/user-guide.html chapter "Escaping VTL Directives" – EagleRainbow Jul 24 '16 at 09:35

6 Answers6

88

this:

#[[
##
]]#

will yield:

##

anything within #[[ ... ]]# is unparsed.

alvi
  • 2,622
  • 1
  • 22
  • 34
  • 1
    Exactly what I needed! The above code generates `\n##\n` though, so just use `#[[##]]#` if you don't want empty lines before and after the `##`. – adentinger Jun 02 '22 at 22:19
51

If you don't want to bother with the EscapeTool, you can do this:

#set( $H = '#' )
$H$H
Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
Nathan Bubna
  • 6,823
  • 2
  • 35
  • 36
6

Maybe, the following site helps? http://velocity.apache.org/tools/1.4/generic/EscapeTool.html

starwarswii
  • 2,187
  • 1
  • 16
  • 19
Thomas
  • 999
  • 8
  • 14
3

Add the esc tool to your toolbox and then you can use ${esc.hash}

Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179
2

${esc.h} will output # as per

this link

Ankit Raonka
  • 6,429
  • 10
  • 35
  • 54
0

The set technique is a good way to get around any characters you need escaping, like if you want to have $name followed by "_lastname" then you can do:

set ($n = '_lastname)

and have this in your template:

$name$n

and it's all good.

gregm
  • 12,019
  • 7
  • 56
  • 78