<" /> <" /> <"/>

How to escape Freemarker output of captured assign?

23 Views Asked by At

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.

2

There are 2 best solutions below

2
ddekany On BEST ANSWER

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>
1
pitgrap On

Found a solution. Convert the markup output to string via builtin ?markup_string. Then it will be escaped automatically.

<div data-test2="${test2?markup_string}"></div>

Output:

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