0

我必须转义 JTwig 模板的所有字符串字段。对于字段,我的意思是每个:{{myfield}}{{myobject.myproperty}}

我知道我可以使用类似的过滤器{{myfield|escape}},但是这种转义应该用于所有字段,所以我想知道是否有一种方法可以使用或覆盖来为每个字符串字段执行全局过滤器。

例如:

public String function filter(String input){
   return input.replaceAll("[^\\x00-\\x7F]", "");
}

(我没有使用 Jtwig 作为 html 模板引擎,而是用于原始文本打印的通用模板引擎。这是转义非 ascii 字符的原因)。

4

1 回答 1

0

我相信您正在寻找默认定义转义模式。在 Jtwig 中有两种方法可以实现这一点。

  1. 定义自定义转义模式并使用 autoescape 标签包装整个模板。
EnvironmentConfiguration configuration = configuration()
  .escape()
    .engines()
      .add("Custom", removeStrangeCharacters())
    .and()
  .and()
.build();
{% autoescape 'Custom' %}{{ myField }}{% endautoescape %}
  1. 定义自定义转义模式并将其设置为 Jtwig 配置中的初始转义模式。
EnvironmentConfiguration configuration = configuration()
  .escape()
    .withInitialEngine("Custom")
    .engines()
      .add("Custom", removeStrangeCharacters())
    .and()
  .and()
.build();
{{ myField }}

您可以在此处找到这两个示例。

于 2016-09-21T20:52:51.547 回答