简体   繁体   English

autoEscape 是真的,但 Ratpack 不会转义 HTML 元素

[英]autoEscape is true but Ratpack doesn't escape HTML elements

With Ratpack 1.6.1 I have a gtpl template with a div element as follows:在 Ratpack 1.6.1 中,我有一个带有 div 元素的 gtpl 模板,如下所示:

div('<pre>HELLO</pre>')

Ratpack doesn't escape the inner pre element even though autoEscape is true .即使autoEscapetrue autoEscape也不会转义内部pre元素。 Is there a way to fix/workaround the issue?有没有办法解决/解决这个问题?

PS autoEscape in TemplateConfiguration is true by default. TemplateConfiguration 中的 PS autoEscape默认为true Setting it to true explicitly doesn't help too:将其显式设置为true也无济于事:

module(MarkupTemplateModule) { TemplateConfiguration config ->
    config.baseTemplateClass = MarkupTemplateExtensions
    config.autoEscape = true
}

Finally figured out the answer:终于找到答案了:

autoEscape doesn't enable escaping in templates. autoEscape不会在模板中启用转义。 It only enables escaping data passed directly into groovyMarkupTemplate like that:它只允许转义直接传递到groovyMarkupTemplate数据,如下所示:

groovyMarkupTemplate('template.gtpl', var: '<pre>Escaped</pre>')

Solution解决方案

In order to enable escaping in all templates by default, it's necessary to subclass BaseTemplate like that:为了默认在所有模板中启用转义,有必要像这样子类BaseTemplate

Apply our own template processor in Ratpack.groovy在 Ratpack.groovy 中应用我们自己的模板处理器

bindings {

   module(MarkupTemplateModule) { TemplateConfiguration config ->
       config.baseTemplateClass = MyMarkupTemplate
   }
}

Subclass BaseTemplate and override methodMissing():子类 BaseTemplate 并覆盖 methodMissing():

@InheritConstructors
abstract class MyMarkupTemplate extends BaseTemplate {
    @Override
    Object methodMissing(String tagName, Object args) {

        if (args instanceof Object[]) {
            Object[] argsArray = (Object[])args

            // Traverse argsArray ans escape every instance of String
            // with XmlUtil.escapeXml()

            return super.methodMissing(tagName, argsArray)
        }

        super.methodMissing(tagName, args)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM