Default escaping in Freemarker

escaping, freemarker, java, xss

Solution

To elaborate on Attila's answer: you can use a class like this one and then wrap your template loader like this:

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 don't include linebreaks in the added parts you don't get the line numbering problem. You can't use the <#ftl>/[#ftl] with this approach, though.

Problem

In Freemarker templates we can use the escape directive to automatically apply an escaping to all interpolations inside the included block: ``` <#escape x as x?html> <#-- name is escaped as html --> Hallo, ${name} </#escape> ``` Is there a way to programmatically achieve a similar effect, defining a default escape applied to all interpolations in the template, including those outside escape directives? Thanks.

Original source