How to output ${expression} in Freemarker without

2019-01-14 11:24发布

I'm trying to use Freemarker in conjunction with jQuery Templates.

Both frameworks use dollar sign/curly brackets to identify expressions for substitution (or as they're called in freemarker, "interpolations") , e.g. ${person.name} .

So when I define a jQuery Template with expressions in that syntax, Freemarker tries to interpret them (and fails).

I've tried various combinations of escaping the ${ sequence to pass it through Freemarker to no avail - \${, \$\{, $\{, etc.

Inserting a freemarker comment in between the dollar and the curly (e.g. $<#-- -->{expression}) DOES work - but I'm looking for a more concise and elegant solution.

Is there a simpler way to get a Freemarker template to output the character sequence ${?

8条回答
Juvenile、少年°
2楼-- · 2019-01-14 11:38

If ${ is your only problem, then you could use the alternate syntax in the jQuery Templates plugin like this: {{= person.name}}

Maybe a little cleaner than escaping it.

查看更多
疯言疯语
3楼-- · 2019-01-14 11:40

Also, if you have longer sections without FreeMarker markup, you can use <#noparse>...</#noparse>.

If you have this issue a lot, since FreeMarker 2.3.28 you can configure FreeMarker to use [=exp] instead of ${exp}, by setting the interpolation_syntax configuration setting to square_bracket (in the Java API: Configuration cfg; ... cfg.setInterpolationSyntax(Configuration.SQUARE_BRACKET_INTERPOLATION_SYNTAX)). Then ${exp} is just static text for FreeMarker. Do not confuse this setting with the tag_syntax setting, which also can have square_bracket value, but is independent of the interpolation syntax (but you may prefer setting both to square_bracket). See also: https://freemarker.apache.org/docs/dgui_misc_alternativesyntax.html

查看更多
聊天终结者
4楼-- · 2019-01-14 11:40

Another option is to use #include with parse=false option. That is, put your jQuery Templates into the separate include page and use parse=false so that freemarker doesn't try and parse it.

This would be a good option when the templates are larger and contain double quotes.

查看更多
孤傲高冷的网名
5楼-- · 2019-01-14 11:42

I had to spent some time to figure out the following scenarios to escape ${expression} -

  • In Freemarker assignment:

<#assign var = r"${expression}">

  • In html attribute:

<a href="/user/${r"${expression}"}"> Some link </a>

  • In Freemarker concatenation:

<#assign x = "something&"+r"${expression}"/>

查看更多
甜甜的少女心
6楼-- · 2019-01-14 11:46

This should print ${person.name}:

${r"${person.name}"}
查看更多
别忘想泡老子
7楼-- · 2019-01-14 11:47

Did you try $$?

I found from the Freemarker manual that ${r"${person.name}"} will print out ${person.name} without attempting to render it.

Perhaps you should also take a look at Freemarker escaping freemarker

查看更多
登录 后发表回答