开发者

Freemarker escaping freemarker

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


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜