我必须逃脱JTWIG模板的所有字符串字段。对于字段,我的意思是:{{myfield}}
或{{myobject.myproperty}}
我知道我可以使用诸如{{myfield|escape}}
之类的过滤器,但是该逃脱应用于所有字段,因此我想知道是否有使用方法或替代每个字符串字段的全局过滤器。p>例如:
public String function filter(String input){
return input.replaceAll("[^\x00-\x7F]", "");
}
(我不是使用JTwig作为HTML模板引擎,而是用于原始文本打印的通用模板引擎。这是逃脱非ASCII Chars的原因)。
我相信您默认要定义逃生模式。在JTwig中,有两种实现这一目标的方法。
- 定义自定义逃生模式并使用自动示例标签包装整个模板。
EnvironmentConfiguration configuration = configuration()
.escape()
.engines()
.add("Custom", removeStrangeCharacters())
.and()
.and()
.build();
{% autoescape 'Custom' %}{{ myField }}{% endautoescape %}
- 定义自定义逃生模式并将其设置为JTwig配置中的初始逃生模式。
EnvironmentConfiguration configuration = configuration()
.escape()
.withInitialEngine("Custom")
.engines()
.add("Custom", removeStrangeCharacters())
.and()
.and()
.build();
{{ myField }}
您可以在这里找到两个示例。