0

With Ratpack 1.6.1 I have a gtpl template with a div element as follows:

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

Ratpack doesn't escape the inner pre element even though autoEscape is true. Is there a way to fix/workaround the issue?

P.S. autoEscape in TemplateConfiguration is true by default. Setting it to true explicitly doesn't help too:

module(MarkupTemplateModule) { TemplateConfiguration config ->
    config.baseTemplateClass = MarkupTemplateExtensions
    config.autoEscape = true
}
Dmitry
  • 1
  • 1
  • 2
    please show more of your code. how do you set autoEscape.. – daggett Apr 01 '20 at 18:41
  • @daggett autoEscape is true by default in TemplateConfiguration. Setting it to true explicitly doesn't help too. Please see the initial comment, I've updated it. – Dmitry Apr 03 '20 at 10:52

1 Answers1

0

Finally figured out the answer:

autoEscape doesn't enable escaping in templates. It only enables escaping data passed directly into groovyMarkupTemplate like that:

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:

Apply our own template processor in Ratpack.groovy

bindings {

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

Subclass BaseTemplate and override 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)
    }
}
Sailor
  • 41
  • 5