4

I am trying to inject a partial html into GTPL file, but it seems always "escapes" html content. How can send HTML snippet to markup and render it directly?

Contents of "hello.gtpl"

yieldUnescaped '<!DOCTYPE html>'
html {
    yieldUnescaped text
}

From ratpack.groovy

    get('helloplain') { //works .but clumsy
        String htmlPayLoad = "<!DOCTYPE html>  <html>  <title> Hello </title><body> <h3> Hello </h3> </body> </html>"
        context.getResponse().contentType(HttpHeaderConstants.HTML_UTF_8).send(htmlPayLoad.getBytes());
    }
    get('hellotemplate') { //ex: /users/
        String text = "<title> Hello </title><body> <h3> Hello </h3> </body> "
        render groovyMarkupTemplate( "hello.gtpl"  ,text: text  )
    }

localhost:5050/helloplain delivers a proper HTML where as localhost:5050/hellotemplate delivers a file that has escaped all HTML content.

<!DOCTYPE html><html>&lt;title&gt; Hello &lt;/title&gt;&lt;body&gt; &lt;h3&gt; Hello &lt;/h3&gt; &lt;/body&gt; </html>

What did I miss?

Jayan
  • 18,003
  • 15
  • 89
  • 143

1 Answers1

6

You need to configure the MarkupTemplateEngine in order to disable auto escaping. Here's a working example using latest stable version of Ratpack.

ratpack.groovy

@Grab('io.ratpack:ratpack-groovy:1.1.1')

import static ratpack.groovy.Groovy.ratpack
import static ratpack.groovy.Groovy.groovyMarkupTemplate
import ratpack.groovy.template.MarkupTemplateModule

ratpack {
  bindings {
    module(MarkupTemplateModule) { config ->
      config.autoEscape = false
    }
   }

  handlers {
    get {
      String text = '<title>Hello</title><body><h3>Hello</h3></body>'
      render groovyMarkupTemplate('hello.gtpl', text: text)
    }
  }
}

templates/hello.gtpl

yieldUnescaped '<!DOCTYPE html>'

html {
  yieldUnescaped text
}

Output of curl against running app

$ curl localhost:5050
<!DOCTYPE html><html><title>Hello</title><body><h3>Hello</h3></body></html>

For a list of which attributes are available for configuration you can check the GDK http://docs.groovy-lang.org/latest/html/gapi/groovy/text/markup/TemplateConfiguration.html

Dan Hyun
  • 536
  • 3
  • 7
  • That affects all requests, correct? Is there a way to restrict select requests? – Jayan Dec 29 '15 at 03:06
  • 1
    @Jayan this should only help `yieldUnescaped` to unescape HTML entities and characters, all other `yield` ing of text should still escape any HTML entities. – Dan Hyun Dec 29 '15 at 05:41
  • Alright.. Accepting the answer, will grant bounty when that is eligible. – Jayan Dec 29 '15 at 06:39