Question

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} ?

Was it helpful?

Solution 2

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}"}

OTHER TIPS

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

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top