在Freemarker模板中,我们可以使用escape指令自动将转义应用于包含块内的所有插值:
<#escape x as x?html>
<#-- name is escaped as html -->
Hallo, ${name}
</#escape>有没有一种方法可以通过编程实现类似的效果,定义一个默认的转义,应用于模板中的所有插值,包括那些外部的转义指令?
谢谢。
发布于 2009-11-05 15:36:58
详述阿提拉的回答:你可以使用像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用于此方法。
发布于 2016-03-30 04:12:33
从2.3.24开始,每个模板都有一个关联的freemarker.core.OutputFormat对象,该对象指定是否以及如何转义${...} (和#{...})。XML和RTF的OuputFormat是开箱即用的,但您也可以定义自己的格式。当选定的OutputFormat在默认情况下转义时,您可以防止像${foo?no_esc}那样显式转义。
有几种方法可以将模板与所需的OutputFormat相关联。对于HTML和XML转义,建议的方法是将recognize_standard_file_extensions配置设置设置为true,然后对HTML使用ftlh文件扩展名,对XML模板使用ftlx文件扩展名。您还可以使用template_configurers设置将OutputFormat-s与基于任意模板名称(模板路径)模式的模板相关联。最后同样重要的是,你可以像configuration.setOutputFormat(HTMLOutputFormat.INSTANCE)一样全局设置默认的输出格式。您也可以覆盖模板顶部的输出格式为<#ftl output_format='HTML'>,尽管它应该很少使用。
相关文档页面:http://freemarker.org/docs/dgui_misc_autoescaping.html、http://freemarker.org/docs/pgui_config_outputformatsautoesc.html
发布于 2009-08-12 12:49:02
有一个解决方案,尽管它不是完全微不足道的。您可以创建一个特殊的TemplateLoader来包装其他模板加载器,并将<#escape x作为x?html>注入到模板源文本的前言中,并将其作为后记添加。
明显的缺点:-第一行的列号会丢失-如果你的模板以<#ftl>声明开始,你需要在它后面插入<#escape>。
https://stackoverflow.com/questions/1265488
复制相似问题