Implement a Groovy TemplateEngine (SimpleTemplateEngine) usage that binds a map of…
- User
Implement a Groovy
TemplateEngine(SimpleTemplateEngine) usage that binds a map of variables to a template string containing JSP-style<% %>logic. Assistant
Implement a Groovy TemplateEngine (SimpleTemplateEngine) usage that binds a map of variables to a template string containing JSP-style <% %> logic.
The user wants to see how to use Groovy's SimpleTemplateEngine.
Specific requirements:
SimpleTemplateEngine (or TemplateEngine concept, but SimpleTemplateEngine is the standard implementation for this).<% %> logic.Plan:
groovy.text.SimpleTemplateEngine, groovy.text.Template, and potentially java.io.* or standard Groovy dependencies.<%= variable %> (for printing) and scriptlets like <% for (...) { %> ... <% } %> (for logic).Map containing the data to be injected into the template.new SimpleTemplateEngine().engine.createTemplate(templateString).template.make(binding).toString() on the result.Code Structure:
import groovy.text.SimpleTemplateEngine
// 1. Define the template string with JSP-style logic
String templateText = """
<%
// JSP-style scriptlet logic
def total = 0
items.each { item ->
total += item.price
%>
<h1>Invoice: <%= title %></h1>
<ul>
<%
items.each { item -> // Iteration logic
%>
<li><%= item.name %> - $<%= item.price %></li>
<%
}
%>
</ul>
<p>Total: $<%= total %></p>
"""
// 2. Define the binding (variables map)
def binding = [
title: "My Shopping Cart",
items: [
[name: "Apple", price: 1.50],
[name: "Banana", price: 0.75],
[name: "Orange", price: 2.00]
]
]
// 3. Implementation
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(templateText)
def writable = template.make(binding)
println writable.toString()
Refinement:
The logic inside the <% %> block in the example above has a slight issue. In JSP/Groovy templates, variables declared in one scriptlet block might need to be accessible in another.
If I calculate total inside the first block, I need to make sure the scope allows it to be printed later.
Actually, SimpleTemplateEngine compiles the template into a Groovy class. The code inside <% %> blocks gets inserted into a method. Local variables defined in one block should be available in subsequent blocks within the same template run because they are essentially concatenated into the same method body before execution.
Let's double-check the syntax.
<% code %>: Executes code but prints nothing.
<%= expression %>: Evaluates expression and prints result.
Example of logic:
String template = """
<% if (showGreeting) { %>
Hello <%= name %>!
<% } else { %>
Goodbye.
<% } %>
"""
This looks correct. I will provide a complete, runnable script.
Potential Pitfalls:
SimpleTemplateEngine can throw ClassNotFoundException if the Groovy jar isn't there, but usually, this is run in a Groovy environment.Final Code Construction: I will write a script that demonstrates:
<%= var %>).<% for ... %>).<% if ... %>).Let's construct the example.
import groovy.text.SimpleTemplateEngine
import groovy.text.Template
// The template string using JSP style <% ... %> and <%= ... %>
def templateString = '''
Report for: <%= userName %>
Date: <%= date %>
<% if (items) { %>
Items List:
<% items.eachWithIndex { item, index -> %>
<%= index + 1 %>. <%= item.key %> : <%= item.value %>
<% } %>
<% } else { %>
No items found.
<% } %>
'''
// The map of variables to bind
def binding = [
userName: "Alice",
date: new Date().format("yyyy-MM-dd"),
items: [
[key: "Laptop", value: "\$1200"],
[key: "Mouse", value: "\$25"]
]
]
// Usage
def engine = new SimpleTemplateEngine()
def template = engine.createTemplate(templateString)
def output = template.make(binding).toString()
println output
This looks solid. I will present the code clearly. I should also mention that StreamingTemplateEngine is an alternative for large templates, but the user specifically asked for SimpleTemplateEngine usage.
I will format the answer with:
SimpleTemplateEngine to bind a map of variables to a string containing JSP-style <% %> scriptlets and <%= %> expressions.import groovy.text.SimpleTemplateEngine
import groovy.text.Template
// 1. Define the Template String
// Uses standard JSP syntax:
// <% ... %> for logic (loops, conditions)
// <%= ... %> for printing variables
def templateText = '''
<%--
Groovy Template Example
--%>
Dear <%= name %>,
Here is the report for the year <%= year %>:
<% if (projects.isEmpty()) { %>
No projects found.
<% } else { %>
<ul>
<% projects.each { project -> %>
<li>
<strong><%= project.name %></strong>
<% if (project.status == "Critical") { %>
<span style="color:red">[CRITICAL]</span>
<% } %>
- Assigned to: <%= project.lead %>
</li>
<% } %>
</ul>
<% } %>
Total Projects: <%= projects.size() %>
'''
// 2. Define the Data (Binding Map)
// These keys will become local variables inside the template
def binding = [
name: "Dev Team",
year: 2023,
projects: [
[name: "Project Alpha", lead: "Alice", status: "Normal"],
[name: "Project Beta", lead: "Bob", status: "Critical"],
[name: "Project Gamma", lead: "Charlie", status: "Normal"]
]
]
try {
// 3. Create and Execute the Template
def engine = new SimpleTemplateEngine()
// Compile the template string
Template template = engine.createTemplate(templateText)
// Merge the template with the binding map
// The make() method returns a Writable object
def writableOutput = template.make(binding)
// Convert to string and print
println writableOutput.toString()
} catch (Exception e) {
e.printStackTrace()
}
When you run the code above, the engine processes the logic and variables to produce:
Dear Dev Team,
Here is the report for the year 2023:
<ul>
<li>
<strong>Project Alpha</strong>
- Assigned to: Alice
</li>
<li>
<strong>Project Beta</strong>
<span style="color:red">[CRITICAL]</span>
- Assigned to: Bob
</li>
<li>
<strong>Project Gamma</strong>
- Assigned to: Charlie
</li>
</ul>
Total Projects: 3
binding map (e.g., name, projects) are automatically available as variables inside the template script.<% %>: Arbitrary Groovy code can be placed here (loops, if statements, variable declarations). The code executes but does not print anything to the output directly.<%= %>: The result of the expression inside is evaluated and converted to a String, then inserted into the output.SimpleTemplateEngine preserves whitespace strictly. Notice in the output how there are blank lines where the if/else logic blocks were in the template string. If you need cleaner output, you often have to "gulp" whitespace (e.g., <% } %> on the same line as content).Not yet included in a published release.