Satyajit Patnaik Satyajit Patnaik - 9 days ago 5
Java Question

How to escape '&' in data coming from webservice in freemarker template?

Freemarker:

If my data is:

x = [{
name= satyajit,
company = hewlett & packard
}, {
name= akanksha,
company = google & co
}]


Following is how I want to access the above list in ftl template.

${x}


But, the above code throws an error saying: The entity name must immediately follow the '&' in the entity reference.

Is there a way to escape the '&' in the data, like the '&' in 'hewlett & packard' from the webservice data in freemarker template?

EDIT:

Error faced:

[Fatal Error] NewFile.xml:27:57: The entity name must immediately follow the '&' in the entity reference.
Exception in thread "main" org.xml.sax.SAXParseException; systemId: file:/D:/NewFile.xml; lineNumber: 27; columnNumber: 57; The entity name must immediately follow the '&' in the entity reference.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)

Answer

Wrap blocks of text in <#escape x as x?html> directives.

public static final String ESCAPE_PREFIX = "<#ftl strip_whitespace=true><#escape x as x?html>";

public static final String ESCAPE_SUFFIX = "</#escape>";

ESCAPE_PREFIX + templateText + ESCAPE_SUFFIX

Refer:http://freemarker.org/docs/dgui_misc_autoescaping.html

http://watchitlater.com/blog/2011/10/default-html-escape-using-freemarker/

Comments