javahtmlfrontendescapingfreemarker

How to escape Freemarker output of captured assign?


I want to escape the output of a variable, that used the capture syntax of a <#assign> in Example 2.

Example 1:

<#assign test1='{"json": "more"}' />
<div data-test1="${test1}"></div>

Output (escaped):

<div data-test1="{&quot;json&quot;: &quot;more&quot;}"></div>

Example 2:

<#assign test2><@compress single_line=true>
{
  "json": "because it is more complex with list, if else etc."
}
</@compress></#assign>
<div data-test2="${test2}"></div>

Output (not escaped):

<div data-test2="{ "json": "because it is more complex with list, if else etc." }"></div>

This is exactly how the docs are describing this feature. Also the docs for escaping.

I need to use the second example, because test2 is more complex to generate. Is there a way to force the escaping or to convert the non-markup output to markup? I tried ?esc, <#outputformat> <#autoesc>, reassigning to another variable. Nothing works.


Solution

  • You need to put the section where you capture that generated JSON inside <#outputformat "JSON">...</#outputformat>. (plainText, or any non-markup output format also will work well, as far as not suppressing escaping inside a markup goes.)

    <#outputformat "JSON">
    <#assign test2><@compress single_line=true>
    {
      "json": "because it is more complex with list, if else etc."
    }
    </@compress></#assign>
    </#outputformat>
    <div data-test2="${test2}"></div>