Java – escape in FreeMarker by default
•
Java
In the FreeMarker template, we can use the escape instruction to automatically apply escape to all interpolation in the included block:
<#escape x as x?html> <#-- name is escaped as html --> Hallo,${name} </#escape>
Is there any way to achieve a similar effect programmatically by defining the Default Escape applied to all interpolation in the template, including interpolation other than escape instructions?
thank you.
Solution
Explain Attila's answer in detail: you can use a class like this one, and then wrap your template loader as follows:
final TemplateLoader templateLoader = new ClasstemplateLoader(this.getClass(),templatePath) { /** * Replaces the normal template reader with something that changes the default * escaping to HTML as to avoid XSS attacks. */ @Override public Reader getReader(Object templateSource,String encoding) throws IOException { return new WrappingReader(super.getReader(templateSource,encoding),"<#escape x as x?html>","</#escape>"); } };
If you do not include line breaks in the added section, you will not get line number problems However, you cannot use < #ftl > / [#ftl]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码