在Freemarker模板中,我们可以使用escape指令自动将转义应用于包含的块中的所有插值:
<#escape x as x?html>
<#-- name is escaped as html -->
Hallo,${name}
</#escape>
有没有办法以编程方式实现类似的效果,定义应用于模板中所有内插的默认转义,包括转义指令之外的内插?
谢谢.
解决方法
详细说明Attila的答案:您可以使用像
this one这样的类,然后如下所示包装你的模板加载器:
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>");
}
};
如果您在添加的部分中不包括换行符,则不会得到行号问题.但是,您不能使用<#ftl> / [#ftl].