在Freemarker中默认转义 [英] Default escaping in 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屋!