0
# Basic Template Engines
1
2
The basic template engines (SimpleTemplateEngine and GStringTemplateEngine) provide JSP-style and GString templating capabilities for generating dynamic text content.
3
4
## SimpleTemplateEngine
5
6
The SimpleTemplateEngine processes templates with JSP-style `<% %>` script blocks and `<%= %>` expressions, plus GString-style `${...}` expressions. It compiles templates to Groovy scripts for execution.
7
8
### API
9
10
```java { .api }
11
class SimpleTemplateEngine extends TemplateEngine {
12
SimpleTemplateEngine();
13
SimpleTemplateEngine(boolean verbose);
14
SimpleTemplateEngine(ClassLoader parentLoader);
15
SimpleTemplateEngine(GroovyShell groovyShell);
16
17
Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException;
18
void setVerbose(boolean verbose);
19
boolean isVerbose();
20
void setEscapeBackslash(boolean escapeBackslash);
21
boolean isEscapeBackslash();
22
}
23
```
24
25
### Template Syntax
26
27
- **Script blocks**: `<% ... %>` - Execute Groovy code
28
- **Expression blocks**: `<%= ... %>` - Output expression result
29
- **GString expressions**: `${...}` and `$variable` - Variable interpolation
30
- **Output variable**: `out` - PrintWriter bound to template output
31
32
### Usage Examples
33
34
#### Basic Template with Mixed Syntax
35
36
```java
37
import groovy.text.SimpleTemplateEngine;
38
import groovy.text.Template;
39
import java.util.HashMap;
40
import java.util.Map;
41
42
SimpleTemplateEngine engine = new SimpleTemplateEngine();
43
44
String templateText = """
45
Dear <%= firstname %> ${lastname},
46
47
We <% if (accepted) print 'are pleased' else print 'regret' %> \\
48
to inform you that your paper entitled
49
'$title' was ${ accepted ? 'accepted' : 'rejected' }.
50
51
The conference committee.
52
""";
53
54
Template template = engine.createTemplate(templateText);
55
56
Map<String, Object> binding = new HashMap<>();
57
binding.put("firstname", "Grace");
58
binding.put("lastname", "Hopper");
59
binding.put("accepted", true);
60
binding.put("title", "Groovy for COBOL programmers");
61
62
String result = template.make(binding).toString();
63
```
64
65
#### Template from File
66
67
```java
68
import java.io.File;
69
import java.nio.charset.StandardCharsets;
70
71
SimpleTemplateEngine engine = new SimpleTemplateEngine();
72
File templateFile = new File("template.gsp");
73
74
// With auto-detected encoding
75
Template template = engine.createTemplate(templateFile);
76
77
// With explicit encoding
78
Template template2 = engine.createTemplate(templateFile, StandardCharsets.UTF_8);
79
80
// Apply binding
81
String result = template.make(binding).toString();
82
```
83
84
#### Verbose Mode for Debugging
85
86
```java
87
SimpleTemplateEngine engine = new SimpleTemplateEngine(true);
88
// or
89
engine.setVerbose(true);
90
91
// This will print generated script source to System.out
92
Template template = engine.createTemplate(templateText);
93
```
94
95
#### Backslash Escaping
96
97
```java
98
SimpleTemplateEngine engine = new SimpleTemplateEngine();
99
engine.setEscapeBackslash(true); // Handle \$ and \< sequences
100
101
String templateText = "Price: \\$${price}"; // Outputs: Price: $100
102
```
103
104
### Servlet Integration
105
106
```xml
107
<!-- web.xml -->
108
<servlet>
109
<servlet-name>SimpleTemplate</servlet-name>
110
<servlet-class>groovy.servlet.TemplateServlet</servlet-class>
111
<init-param>
112
<param-name>template.engine</param-name>
113
<param-value>groovy.text.SimpleTemplateEngine</param-value>
114
</init-param>
115
</servlet>
116
```
117
118
## GStringTemplateEngine
119
120
The GStringTemplateEngine provides equivalent functionality to SimpleTemplateEngine but uses a streaming closure-based approach, making it more scalable for large templates.
121
122
### API
123
124
```java { .api }
125
class GStringTemplateEngine extends TemplateEngine {
126
GStringTemplateEngine();
127
GStringTemplateEngine(ClassLoader parentLoader);
128
129
Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException;
130
}
131
```
132
133
### Template Syntax
134
135
Same as SimpleTemplateEngine:
136
- **Script blocks**: `<% ... %>` - Execute Groovy code
137
- **Expression blocks**: `<%= ... %>` - Output expression result
138
- **GString expressions**: `${...}` and `$variable` - Variable interpolation
139
- **Output variable**: `out` - PrintWriter bound to template output
140
141
### Usage Examples
142
143
#### Basic Usage
144
145
```java
146
import groovy.text.GStringTemplateEngine;
147
import groovy.text.Template;
148
149
GStringTemplateEngine engine = new GStringTemplateEngine();
150
151
String templateText = """
152
Hello <%= name %>!
153
Your balance is ${currency}${balance}.
154
<% if (balance > 1000) { %>
155
You qualify for premium service!
156
<% } %>
157
""";
158
159
Template template = engine.createTemplate(templateText);
160
161
Map<String, Object> binding = new HashMap<>();
162
binding.put("name", "Alice");
163
binding.put("currency", "$");
164
binding.put("balance", 1500);
165
166
String result = template.make(binding).toString();
167
```
168
169
#### Custom Class Loader
170
171
```java
172
ClassLoader customLoader = MyClass.class.getClassLoader();
173
GStringTemplateEngine engine = new GStringTemplateEngine(customLoader);
174
175
Template template = engine.createTemplate(templateSource);
176
```
177
178
### Performance Characteristics
179
180
- **Memory efficient**: Uses closures instead of string concatenation
181
- **Scalable**: Better performance for large templates
182
- **Streaming**: Generates output incrementally
183
- **Garbage collection friendly**: Less intermediate string creation
184
185
### Servlet Integration
186
187
```xml
188
<!-- web.xml -->
189
<servlet>
190
<servlet-name>GStringTemplate</servlet-name>
191
<servlet-class>groovy.servlet.TemplateServlet</servlet-class>
192
<init-param>
193
<param-name>template.engine</param-name>
194
<param-value>groovy.text.GStringTemplateEngine</param-value>
195
</init-param>
196
</servlet>
197
```
198
199
## Choosing Between SimpleTemplateEngine and GStringTemplateEngine
200
201
### Use SimpleTemplateEngine when:
202
- Working with small to medium templates
203
- Need verbose debugging output
204
- Require backslash escaping features
205
- Simple deployment requirements
206
207
### Use GStringTemplateEngine when:
208
- Working with large templates
209
- Memory efficiency is important
210
- High-performance template rendering
211
- Streaming output scenarios
212
213
## Common Error Handling
214
215
Both engines throw the same exceptions:
216
217
```java
218
import groovy.text.TemplateExecutionException;
219
import groovy.text.TemplateParseException;
220
import org.codehaus.groovy.control.CompilationFailedException;
221
222
try {
223
Template template = engine.createTemplate(templateSource);
224
String result = template.make(binding).toString();
225
} catch (TemplateParseException e) {
226
// Template syntax error
227
System.err.println("Parse error at line " + e.getLineNumber() +
228
", column " + e.getColumn() + ": " + e.getMessage());
229
} catch (CompilationFailedException e) {
230
// Groovy compilation error
231
System.err.println("Compilation failed: " + e.getMessage());
232
} catch (TemplateExecutionException e) {
233
// Runtime error during template execution
234
System.err.println("Execution error at line " + e.getLineNumber() +
235
": " + e.getMessage());
236
} catch (Exception e) {
237
// Other errors (IO, ClassNotFound, etc.)
238
System.err.println("Template error: " + e.getMessage());
239
}
240
```