在Freemarker中默认转义 [英] Default escaping in Freemarker

查看:1792
本文介绍了在Freemarker中默认转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < p>在Freemarker模板中,我们可以使用escape指令自动将转义应用于包含的块中的所有内插: ; #escape x as x?html> 
<# - 名称被转义为html - >
Hallo,$ {name}
< /#escape>

有没有办法以编程方式实现类似的效果,定义应用于所有内插的默认转义



谢谢。

解决方案

要详细说明Attila的答案:您可以使用类似这个,然后包装你的模板加载器,如下所示:

  final TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(),templatePath){
/ **
*用更改默认值的东西替换普通模板阅读器
*转义为HTML,以避免XSS攻击。
* /
@Override
public Reader getReader(Object templateSource,String encoding)throws IOException {
return new WrappingReader(super.getReader(templateSource,encoding),<#将x转换为x?html>,< /#escape>);
}
};

如果您在添加的部分中不包括换行符,则不会得到行号问题。尽管如此,您不能使用< #ftl> / [#ftl]。


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.

解决方案

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.

这篇关于在Freemarker中默认转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆