Search code examples
javafreemarker

freemarker display ${..} as html rather than string


I get html code from server to build freemarker.ftl. Example:

Server return: String htmlCode="<h1>Hello</h1>";

freemarker.ftl

${htmlCode}

except:

Hello

actually: <h1>Hello</h1>

what can i do?


Solution

  • Update: FreeMarker 2.3.24 introduced auto-escaping, which will be on in projects that follow best practices. Typically, the default output_format is configured to be HTML (or the ftlh file extension is used instead of ftl, or the file starts with <#ftl output_format='HTML'>). Then the output of ${x} will be always escaped. To prevent that, use ${x?no_esc}. In a such configuration #noescape and #escape will give error anyway, so you will know that you have auto-escaping. See also: https://freemarker.apache.org/docs/dgui_misc_autoescaping.html

    Original (outdated) answer:

    By default FreeMarker has no auto-escaping on, so it should print that value as HTML. But as it doesn't as you say, I can imagine two possibilities:

    • You are inside <#escape x as x?html>...</#escape>, or that was added to the template by a custom TemplateLoader. In that case, in 2.3.x you have to write <#noescape>${htmlCode}</#noescape>.
    • That value was escaped before it reaches FreeMarker. So the template already gets &lt;h1&gt;Hello&lt;/h1&gt; as the string.