7

I'm using freemarker to generate a freemarker template. But I need some way to escape freemarker tags.

How would I escape a <#list> tag or a ${expression} ?

Pat
  • 25,237
  • 6
  • 71
  • 68
tuler
  • 3,339
  • 7
  • 34
  • 44

4 Answers4

11

You could also use: ${"$"}{expression} if you find the {} nesting confusing.

monzonj
  • 3,659
  • 2
  • 32
  • 27
  • The best of all alternatives suggested to date. Boggles my mind that there isn't a simpler way, such as `\$` - but there ain't. This is a good enough approximation of elegance... – Stevel Jun 27 '17 at 20:13
  • unlike the other solution, this works even when there are quotes in the literal. – ths Feb 02 '23 at 16:42
8

I'm using the alternative syntax feature. I start the template with [#ftl] and use this syntax.

For the expressions I use the string literal feature: ${r"${expression}"}

Pat
  • 25,237
  • 6
  • 71
  • 68
tuler
  • 3,339
  • 7
  • 34
  • 44
  • I use the same approach, which is a bit ugly but works. It gets really nasty if I use a variable of the outer template to define the property access of a variable of the generated template, which looks like this: ${r"${entity."}${propertyDescriptor.name}} and ends like ${entity.creationDate} given that the propertyDescriptor has the name "creationDate". – Peter Becker Nov 05 '09 at 07:44
1

You can configure FreeMarker to use [=exp] instead of ${exp} (since 2.3.28), and [#...]/[@...] instead of <#...>|<@...> by setting both the interpolation_syntax and the tag_syntax configuration setting to square_bracket (in the Java API: Configuration cfg; ... cfg.setInterpolationSyntax(Configuration.SQUARE_BRACKET_INTERPOLATION_SYNTAX) and cfg.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX)). Then the syntax doesn't clash with the default syntax.

There's one tricky case; if the template starts with <#ftl>, then it will switch the tag syntax back to angle_bracket. To counter that, just add a [#ftl] line before it.

See also: https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html

ddekany
  • 29,656
  • 4
  • 57
  • 64
0

In the case when you want to use non-raw strings so that you can escape double quotes, apostrophes, etc, you can do the following:

Imagine that you want to use the string ${Hello}-"My friend's friend" inside of a string. You cannot do that with raw strings. What I have used that works is:

${"\x0024{Hello}-\"My friend's friend\""}

I have not escaped the apostrophe since I used double quotes.

Jaime Garza
  • 483
  • 1
  • 4
  • 10