JTwig 全局字段过滤器
JTwig global field filter
我必须转义 JTwig 模板的所有字符串字段。
对于字段,我的意思是每个:{{myfield}}
或 {{myobject.myproperty}}
我知道我可以使用像 {{myfield|escape}}
这样的过滤器,但是这个转义应该用于所有字段所以我想知道是否有一种方法可以使用或重写来为每个字符串字段。
例如:
public String function filter(String input){
return input.replaceAll("[^\x00-\x7F]", "");
}
(我没有将 Jtwig 用作 html 模板引擎,而是用于原始文本打印的通用模板引擎。这就是转义非 ascii 字符的原因)。
我相信您希望默认定义一个转义模式。在 Jtwig 中,有两种方法可以实现这一点。
- 定义自定义转义模式并使用autoescape标签包裹整个模板。
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 }}
您可以在 here 中找到这两个示例。
我必须转义 JTwig 模板的所有字符串字段。
对于字段,我的意思是每个:{{myfield}}
或 {{myobject.myproperty}}
我知道我可以使用像 {{myfield|escape}}
这样的过滤器,但是这个转义应该用于所有字段所以我想知道是否有一种方法可以使用或重写来为每个字符串字段。
例如:
public String function filter(String input){
return input.replaceAll("[^\x00-\x7F]", "");
}
(我没有将 Jtwig 用作 html 模板引擎,而是用于原始文本打印的通用模板引擎。这就是转义非 ascii 字符的原因)。
我相信您希望默认定义一个转义模式。在 Jtwig 中,有两种方法可以实现这一点。
- 定义自定义转义模式并使用autoescape标签包裹整个模板。
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 }}
您可以在 here 中找到这两个示例。