FREEMARKER: avoid escaping HTML chars

2019-06-25 13:16发布

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 :(

4条回答
Melony?
2楼-- · 2019-06-25 14:07

So after trying stuff, I don't know what I've done wrong before, but clean, this way is working

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



<select>
   [#noescape]
   ${optionsHTML}
   [/#noescape]
</select>
查看更多
做自己的国王
3楼-- · 2019-06-25 14:08

I faced same problem in string with special chars. In this example I have checknumber = "6547&6548" which caused problem before using this #escape

the best and simple way to handle this as following code

<#escape x as x?html>${deposit.checkNumber}</#escape>
查看更多
可以哭但决不认输i
4楼-- · 2019-06-25 14:08

Like ddekany said, write something like this:

<select>
  [#list data as item]
    <option value="${item.value}">${item.label}</option>
  [/#list]
</select>
查看更多
等我变得足够好
5楼-- · 2019-06-25 14:09

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.

查看更多
登录 后发表回答