FREEMARKER: avoid escaping HTML chars

DS_web_developer picture DS_web_developer · Jun 9, 2014 · Viewed 12.2k times · Source

Having a problem with freemarker output...

                [#assign optionsHTML = ""]                    
                [#list data as item]
                    [#assign optionsHTML = optionsHTML + '<option value="' + item.value +'>'+ item.label + '</option>' /]
                [/#list]

so, if I do

<select>
${iptionsHTML}
</select>

the output from otions get html entities instead of actual html.... so

&lt;option value=&quot .....

even if I do

            [#assign optionsHTML = ""]                    
            [#list data as item]
                [#noescape]
                [#assign optionsHTML = optionsHTML + '<option value="' + item.value +'>'+ item.label + '</option>' /]
                [/#noescape]
            [/#list]

tried even

<select>
${iptionsHTML?html}
</select>

but's even worse :(

Answer

ddekany picture ddekany · Jun 10, 2014

Putting #noescape around #assign has no effect. Automatic escaping only applies to ${...}-s that are embedded directly into the static text (the HTML). So there's no escaping to disable inside that #assign.

?html is used to escape a string "manually". Like in your example you could write optionsHTML = optionsHTML + '<option value="${item.value?html}>${item.label?html}</option>', because you know that the value will be output non-auto-escaped later, and the ${...}-s inside the string literal aren't escaped automatically.

However, the best would be if you can organize your code so that things that generate HTML don't construct the HTML inside variables and then print the variable, but print the HTML directly into the output. That's what FTL is designed for.