Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Builders, DSLs and Templates

Template Engines in Groovy

Generate text, emails and code from templates in Groovy: GString, SimpleTemplateEngine, GStringTemplateEngine, MarkupTemplateEngine and escaping rules.

A template is a text with holes. You fill the holes with data and get a letter, a report, an HTML page, a config file or generated source code. Groovy has template support built into the language (GStrings) and in the standard library (groovy.text). Which to pick depends on how much logic the template needs.

Groovy cannot run on this site, so the Groovy fences are read-only and outputs appear only when exact. The Java stand-ins implement a minimal ${name} replacer and a loop renderer so you can try the idea.

Level 1: GStrings

For small cases the language itself is enough:

GROOVY
def name = "Ada"
def items = 3
println "Hello, ${name}! You have ${items} item${items == 1 ? '' : 's'}."
// Hello, Ada! You have 3 items.

def report = """\
Report for ${name}
------------------
Items: ${items}
"""

A triple-quoted GString spans lines. Values are evaluated immediately when the string is created, and ${ -> value } (a closure inside) delays evaluation until the string is printed.

Use GStrings when the data is already in variables in the same scope. A template engine is for when the template text comes from elsewhere: a file, a database or a user.

Level 2: SimpleTemplateEngine

groovy.text.SimpleTemplateEngine takes template text, then merges it with a map of variables ("the binding"):

GROOVY
import groovy.text.SimpleTemplateEngine

def text = '''Dear ${name},

<% if (balance < 0) { %>Your account is overdrawn by ${-balance}.<% } else { %>Your balance is ${balance}.<% } %>

Items:
<% items.each { %>  - ${it}
<% } %>
Regards
'''

def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(text)

def out = template.make([name: "Ada", balance: -12, items: ["pen", "ink"]]).toString()
println out

The syntax has three forms:

  • ${expression} inserts the value. For a plain $name shorthand there is no escaping, so be careful with HTML.
  • <% code %> runs Groovy statements (loops, conditions).
  • <%= expression %> inserts a value, like ${}.

createTemplate compiles the template once. Call make(binding) as often as you want, so templates scale well: compile at startup, fill per request.

You can load a template from a file or reader: engine.createTemplate(new File("welcome.txt")) or from a URL.

Level 3: GStringTemplateEngine

GStringTemplateEngine uses the same syntax but compiles each template to a closure and caches better, which tends to be faster and supports <% %> in more places. Use it when the same template is rendered many times. It is a drop-in replacement for most SimpleTemplateEngine uses.

Level 4: MarkupTemplateEngine

Introduced for building HTML/XML, groovy.text.markup.MarkupTemplateEngine writes templates as a builder DSL instead of text with holes. The template is a Groovy script:

GROOVY
import groovy.text.markup.MarkupTemplateEngine
import groovy.text.markup.TemplateConfiguration

def config = new TemplateConfiguration()
def engine = new MarkupTemplateEngine(config)

def template = engine.createTemplate('''
  html {
    head { title(pageTitle) }
    body {
      h1 "Hello, $name"
      ul {
        items.each { li it }
      }
    }
  }
''')

println template.make(pageTitle: "Home", name: "Ada", items: ["a", "b"])

Advantages over plain text templates:

  • The output is always well-formed, since you describe elements, not tags.
  • Text is escaped by default (control with yield and yieldUnescaped).
  • It supports type checking (modelTypes) and layouts, include template:, and pretty printing (config.autoIndent = true).
  • It is fast because templates are compiled to bytecode.

Choosing

Need Choose
Short inline text GString
Emails, reports, code generation from a file SimpleTemplateEngine / GStringTemplateEngine
HTML/XML with guaranteed structure MarkupTemplateEngine
Large web app A view library (Thymeleaf, Freemarker, Groovy Server Pages in Grails)

Escaping and safety

  1. Never put untrusted data into HTML through a text template without escaping. SimpleTemplateEngine does not escape. Use MarkupTemplateEngine or escape yourself with groovy.xml.XmlUtil.escapeXml(value).
  2. Never run templates from untrusted authors. <% %> blocks execute arbitrary Groovy code with your permissions. Templates that users write must be a restricted language, not Groovy.
  3. Keep logic out of templates. A loop and a condition are fine; business rules belong in the model you pass in.
flowchart LR
  A["Template text"] --> C["Engine.createTemplate"]
  B["Binding map"] --> D["template.make"]
  C --> D
  D --> E["Rendered output"]

Compile once, render many times with different bindings.

Try it: a minimal ${name} merge (stand-in)

This Java program replaces ${key} placeholders from a map and reports missing keys, like a binding would.

Java Stand-in: placeholder substitution

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: loops and escaping (stand-in)

A template with a repeating section and HTML escaping, as MarkupTemplateEngine does automatically.

Java Stand-in: list rendering with escaping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main advantage of createTemplate followed by make?

    Compiling is the expensive step. make(binding) is cheap, so reuse the compiled template.
  2. 2. Which engine produces HTML through a builder-style DSL and escapes text by default?

    MarkupTemplateEngine templates are builder scripts, so structure is valid and text is escaped.
  3. 3. What does <% items.each { %> ... <% } %> do in SimpleTemplateEngine?

    <% %> blocks contain Groovy statements, so the text between them is repeated for each item.
  4. 4. Why must you not let end users author templates in these engines?

    Scriptlets run with full privileges, which makes untrusted templates a code-execution risk.

Summary

  • GStrings handle small, local text; engines handle templates that come from files or data.
  • SimpleTemplateEngine and GStringTemplateEngine use ${} and <% %>, compile once and make with a binding.
  • MarkupTemplateEngine builds well-formed, escaped HTML/XML with a DSL.
  • Escape untrusted data and never accept templates from untrusted people.

Next: Your First Spock Specification