Groovy Guide — Templates: Generating Text and HTML
In this tutorial, you will learn about Groovy Guide. We cover key concepts, practical examples, and best practices to help you master this topic.
Groovy templates generate dynamic text content using template files with embedded expressions, supporting loops, conditionals, layouts, and reusable components for web pages and reports.
What You'll Learn
- SimpleTemplateEngine
- Template variables
- Loops and conditionals
- Layouts and includes
- Custom template engines
Why It Matters
Templates separate presentation from logic, making content generation maintainable. Durga Antivirus Pro uses templates for report generation.
Real-World Use
HTML email generation, web page rendering, Code Generation, and report formatting.
flowchart LR
A["Templates"] --> B["SimpleTemplate"]
B --> C["Variables"]
C --> D["Loops"]
D --> E["Layouts"]
A:::current --> B
style A fill:#2563eb,stroke:#2563eb,color:#fff
style B fill:#dbeafe,stroke:#2563eb,color:#1e40af
style C fill:#dbeafe,stroke:#2563eb,color:#1e40af
style D fill:#dbeafe,stroke:#2563eb,color:#1e40af
style E fill:#f1f5f9,stroke:#94a3b8,color:#64748b
SimpleTemplateEngine
import groovy.text.SimpleTemplateEngine
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate('Hello, ${name}!')
def binding = [name: "Alice"]
def output = template.make(binding)
println output // "Hello, Alice!"
Template Files
// template.groovy
// Hello, ${name}!
// You are ${age} years old.
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(new File("template.groovy"))
def output = template.make(name: "Alice", age: 30)
println output
Loops in Templates
// template.groovy
// <ul>
// <% items.each { item -> %>
// <li>${item}</li>
// <% } %>
// </ul>
def template = engine.createTemplate(new File("template.groovy"))
def output = template.make(items: ["Apple", "Banana", "Cherry"])
// Output:
// <ul>
// <li>Apple</li>
// <li>Banana</li>
// <li>Cherry</li>
// </ul>
Conditionals
// template.groovy
// <% if (user.admin) { %>
// <span class="admin">Admin</span>
// <% } else { %>
// <span class="user">User</span>
// <% } %>
def template = engine.createTemplate(new File("template.groovy"))
println template.make(user: [name: "Alice", admin: true])
StreamingTemplateEngine
import groovy.text.StreamingTemplateEngine
// More efficient for large templates
def engine = new StreamingTemplateEngine()
def template = engine.createTemplate("Hello, \${name}!")
def output = template.make([:], name: "Alice")
Layout Template
// layout.groovy
// <html>
// <head><title>${title}</title></head>
// <body>
// <h1>${title}</h1>
// ${content}
// </body>
// </html>
// page.groovy
// <% content = capture { %>
// <% items.each { item -> %>
// <p>${item}</p>
// <% } %>
// <% } %>
// <% include 'layout.groovy' %>
Common Mistakes
1. Escaping dollar signs
In template strings, escape $ as $. In template files, $ is the expression marker.
2. Variable scope
Templates have their own scope. Variables from outside must be passed as bindings.
3. Performance with SimpleTemplateEngine
For repeated rendering, cache the template object. Creation has overhead.
4. XSS in web templates
Escape user content: ${content.encodeAsHTML()} or use a web framework's auto-escaping.
5. Nested template syntax
Template expressions inside template expressions are tricky. Break into multiple steps.
Practice Questions
1. What does SimpleTemplateEngine do? Processes template text with embedded Groovy expressions (${}) and scriptlets (<% %>).
2. How do you pass data to a template?
Use template.make(binding) where binding is a map of variable names to values.
3. How do you iterate in a template? Use Groovy's <% items.each { item -> %> ... <% } %> inside template files.
Challenge: Create a template that generates an HTML table from a list of maps.
FAQ
{{< faq question="Is Groovy's template engine production-ready?" >} SimpleTemplateEngine is used in Grails and other frameworks. For high-traffic sites, consider Caching. {{< /faq >}}
{{< faq question="What is the difference between Simple and Streaming template engines?" >} SimpleTemplateEngine builds a full output string. StreamingTemplateEngine writes to a writer for better memory use. {{< /faq >}}
{{< faq question="Can templates call methods?" >} Yes. Any method available in the binding scope is callable from the template. {{< /faq >}}
{{< faq question="How do I include one template in another?" >}
Use the include function inside a template: <% include 'header.groovy' %>.
{{< /faq >}}
{{< faq question="Can templates be internationalized?" >} Yes. Pass locale-specific strings through the binding map. {{< /faq >}}
Mini Project
Build a report template system:
import groovy.text.SimpleTemplateEngine
def engine = new SimpleTemplateEngine()
def reportTemplate = '''
<html>
<head><title>${title}</title></head>
<body>
<h1>${title}</h1>
<p>Generated: ${new Date()}</p>
<table border="1">
<tr><th>Name</th><th>Value</th><th>Status</th></tr>
<% rows.each { row -> %>
<tr>
<td>${row.name}</td>
<td>${row.value}</td>
<td style="color: ${row.status == 'OK' ? 'green' : 'red'}">
${row.status}
</td>
</tr>
<% } %>
</table>
</body>
</html>
'''
def template = engine.createTemplate(reportTemplate)
def output = template.make(
title: "System Report",
rows: [
[name: "CPU", value: "45%", status: "OK"],
[name: "Memory", value: "80%", status: "Warning"],
]
)
new File("report.html").text = output
What's Next
Now that you understand templates, explore testing in Groovy.
| Topic | Description | Link |
|---|---|---|
| Groovy Testing | Unit Testing | {{< ref "15-testing" >}} |
| Groovy Spock | Spock framework | {{< ref "16-spock" >}} |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro