0
# Core Template Processing
1
2
This document covers the essential classes and methods for template loading, configuration, and processing in Apache FreeMarker.
3
4
## Configuration
5
6
The `Configuration` class is the main entry point for FreeMarker. It manages global settings, template loading, and serves as a factory for Template instances.
7
8
### Basic Configuration Setup
9
10
```java { .api }
11
class Configuration extends Configurable implements Cloneable, ParserConfiguration {
12
// Constructors
13
Configuration(Version incompatibleImprovements);
14
15
// Template loading methods
16
Template getTemplate(String name) throws IOException;
17
Template getTemplate(String name, Locale locale) throws IOException;
18
Template getTemplate(String name, Locale locale, String encoding) throws IOException;
19
Template getTemplate(String name, Locale locale, String encoding, boolean parseAsFTL) throws IOException;
20
21
// Template loader configuration
22
void setDirectoryForTemplateLoading(File dir) throws IOException;
23
void setClassForTemplateLoading(Class resourceLoaderClass, String basePackagePath);
24
void setTemplateLoader(TemplateLoader templateLoader);
25
void setTemplateLookupStrategy(TemplateLookupStrategy templateLookupStrategy);
26
void setTemplateNameFormat(TemplateNameFormat templateNameFormat);
27
28
// Object wrapping configuration
29
void setObjectWrapper(ObjectWrapper objectWrapper);
30
ObjectWrapper getObjectWrapper();
31
32
// Encoding and locale settings
33
void setDefaultEncoding(String encoding);
34
String getDefaultEncoding();
35
void setLocale(Locale locale);
36
Locale getLocale();
37
void setTimeZone(TimeZone timeZone);
38
TimeZone getTimeZone();
39
40
// Output format configuration
41
void setOutputFormat(OutputFormat outputFormat);
42
OutputFormat getOutputFormat();
43
void setRegisteredCustomOutputFormats(Collection<? extends OutputFormat> registeredCustomOutputFormats);
44
45
// General configuration methods
46
void setSetting(String name, String value) throws TemplateException;
47
String getSetting(String key);
48
Properties getSettings() throws TemplateException;
49
Version getVersion();
50
Version getIncompatibleImprovements();
51
52
// Cache configuration
53
void setCacheStorage(CacheStorage cacheStorage);
54
CacheStorage getCacheStorage();
55
void clearTemplateCache();
56
void removeTemplateFromCache(String name);
57
void removeTemplateFromCache(String name, Locale locale);
58
void removeTemplateFromCache(String name, Locale locale, String encoding);
59
60
// Exception handling
61
void setTemplateExceptionHandler(TemplateExceptionHandler templateExceptionHandler);
62
TemplateExceptionHandler getTemplateExceptionHandler();
63
void setAttemptExceptionReporter(AttemptExceptionReporter attemptExceptionReporter);
64
AttemptExceptionReporter getAttemptExceptionReporter();
65
66
// Auto-escaping and output formats
67
void setAutoEscapingPolicy(int autoEscapingPolicy);
68
int getAutoEscapingPolicy();
69
void setRecognizeStandardFileExtensions(boolean recognizeStandardFileExtensions);
70
boolean getRecognizeStandardFileExtensions();
71
}
72
```
73
74
### Configuration Usage Examples
75
76
```java
77
// Basic file-based configuration
78
Configuration cfg = new Configuration(Configuration.VERSION_2_3_34);
79
cfg.setDirectoryForTemplateLoading(new File("/path/to/templates"));
80
cfg.setDefaultEncoding("UTF-8");
81
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
82
83
// Classpath-based configuration
84
Configuration cfg = new Configuration(Configuration.VERSION_2_3_34);
85
cfg.setClassForTemplateLoading(MyClass.class, "/templates");
86
cfg.setDefaultEncoding("UTF-8");
87
88
// Custom object wrapper
89
Configuration cfg = new Configuration(Configuration.VERSION_2_3_34);
90
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_34));
91
92
// Auto-escaping configuration
93
cfg.setAutoEscapingPolicy(Configuration.ENABLE_IF_DEFAULT_AUTO_ESCAPING_POLICY);
94
cfg.setOutputFormat(HTMLOutputFormat.INSTANCE);
95
```
96
97
## Template
98
99
The `Template` class represents a parsed template ready for processing.
100
101
```java { .api }
102
class Template extends Configurable {
103
// Constructors
104
Template(String name, Reader reader, Configuration cfg) throws IOException;
105
Template(String name, Reader reader, Configuration cfg, String encoding) throws IOException;
106
Template(String name, String sourceCode, Configuration cfg) throws IOException;
107
108
// Processing methods
109
void process(Object dataModel, Writer out) throws TemplateException, IOException;
110
void process(Object dataModel, Writer out, ObjectWrapper wrapper) throws TemplateException, IOException;
111
void process(Object dataModel, Writer out, ObjectWrapper wrapper, Locale locale) throws TemplateException, IOException;
112
113
// Environment creation
114
Environment createProcessingEnvironment(Object dataModel, Writer out) throws TemplateException, IOException;
115
Environment createProcessingEnvironment(Object dataModel, Writer out, ObjectWrapper wrapper) throws TemplateException, IOException;
116
117
// Template information
118
String getName();
119
String getEncoding();
120
Configuration getConfiguration();
121
Object getCustomLookupCondition();
122
Version getTemplateLanguageVersion();
123
String getSourceName();
124
125
// Processing control
126
void setCustomAttribute(Object key, Object value);
127
Object getCustomAttribute(Object key);
128
void removeCustomAttribute(Object key);
129
Enumeration getCustomAttributeNames();
130
}
131
```
132
133
### Template Usage Examples
134
135
```java
136
// Basic template processing
137
Template template = cfg.getTemplate("hello.ftl");
138
Map<String, Object> dataModel = new HashMap<>();
139
dataModel.put("user", "John Doe");
140
141
Writer out = new StringWriter();
142
template.process(dataModel, out);
143
String result = out.toString();
144
145
// Processing with custom wrapper
146
Template template = cfg.getTemplate("advanced.ftl");
147
ObjectWrapper wrapper = new DefaultObjectWrapper(Configuration.VERSION_2_3_34);
148
template.process(dataModel, out, wrapper);
149
150
// Creating processing environment for advanced control
151
Environment env = template.createProcessingEnvironment(dataModel, out);
152
env.setGlobalVariable("currentTime", new SimpleDate(new Date(), TemplateDateModel.DATETIME));
153
env.process();
154
```
155
156
## Environment
157
158
The `Environment` class represents the runtime context during template processing.
159
160
```java { .api }
161
class Environment extends Configurable {
162
// Processing control
163
void process() throws TemplateException, IOException;
164
void include(Template template) throws TemplateException, IOException;
165
void include(String name) throws TemplateException, IOException;
166
void visit(TemplateNodeModel node) throws TemplateException, IOException;
167
void visit(TemplateNodeModel node, TemplateSequenceModel namespaces) throws TemplateException, IOException;
168
169
// Namespace management
170
TemplateHashModel getCurrentNamespace() throws TemplateException;
171
TemplateHashModel getMainNamespace();
172
TemplateHashModel getDataModel();
173
174
// Variable management
175
void setGlobalVariable(String name, TemplateModel model) throws TemplateException;
176
void setVariable(String name, TemplateModel model) throws TemplateException;
177
void setLocalVariable(String name, TemplateModel model) throws TemplateException;
178
TemplateModel getGlobalVariable(String name) throws TemplateException;
179
TemplateModel getVariable(String name) throws TemplateException;
180
TemplateModel getLocalVariable(String name) throws TemplateException;
181
182
// Context information
183
Object getDataModel();
184
Writer getOut();
185
Template getTemplate();
186
TemplateNodeModel getCurrentVisitorNode() throws TemplateException;
187
TemplateModel getNodeProcessor(String nodeName) throws TemplateException;
188
189
// Directive and transform management
190
TemplateTransformModel getTransform(String key) throws TemplateException;
191
void visitByHiddingParent(TemplateNodeModel node) throws TemplateException, IOException;
192
void invokeDirective(String directiveName, Map parameters, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException;
193
194
// URL and import utilities
195
String toFullTemplateName(String baseName, String targetName) throws TemplateException;
196
TemplateModel getLastReturnValue();
197
Locale getLocale();
198
void setOut(Writer out);
199
200
// Error handling context
201
void outputInstructionStack(PrintWriter pw);
202
String getCurrentRecursionStepLocation() throws TemplateException;
203
}
204
```
205
206
### Environment Usage Examples
207
208
```java
209
// Advanced template processing with environment control
210
Template template = cfg.getTemplate("complex.ftl");
211
Environment env = template.createProcessingEnvironment(dataModel, out);
212
213
// Set global variables accessible throughout template processing
214
env.setGlobalVariable("appName", new SimpleScalar("MyApplication"));
215
env.setGlobalVariable("buildNumber", new SimpleNumber(12345));
216
217
// Process the template
218
env.process();
219
220
// Access processing results
221
Object lastReturn = env.getLastReturnValue();
222
```
223
224
## Processing Lifecycle
225
226
The typical FreeMarker processing lifecycle follows these steps:
227
228
1. **Configuration Setup**: Create and configure a `Configuration` instance
229
2. **Template Loading**: Use `Configuration.getTemplate()` to load and parse templates
230
3. **Data Model Preparation**: Prepare Java objects as the data model
231
4. **Template Processing**: Call `Template.process()` or create an `Environment` for advanced control
232
5. **Output Generation**: FreeMarker generates output by merging template with data
233
234
### Complete Processing Example
235
236
```java
237
// 1. Configuration setup
238
Configuration cfg = new Configuration(Configuration.VERSION_2_3_34);
239
cfg.setDirectoryForTemplateLoading(new File("templates"));
240
cfg.setDefaultEncoding("UTF-8");
241
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
242
cfg.setLogTemplateExceptions(false);
243
cfg.setWrapUncheckedExceptions(true);
244
245
// 2. Data model preparation
246
Map<String, Object> root = new HashMap<>();
247
root.put("user", new User("John", "Doe"));
248
root.put("products", getProducts());
249
root.put("latestProduct", getLatestProduct());
250
251
// 3. Template loading and processing
252
Template template = cfg.getTemplate("product-catalog.ftl");
253
Writer out = new FileWriter("output.html");
254
template.process(root, out);
255
out.close();
256
```
257
258
## Configuration Constants
259
260
```java { .api }
261
// Version constants
262
static final Version VERSION_2_3_0 = new Version(2, 3, 0);
263
static final Version VERSION_2_3_34 = new Version(2, 3, 34);
264
265
// Auto-escaping policy constants
266
static final int DISABLE_AUTO_ESCAPING_POLICY = 20;
267
static final int ENABLE_IF_DEFAULT_AUTO_ESCAPING_POLICY = 21;
268
static final int ENABLE_IF_SUPPORTED_AUTO_ESCAPING_POLICY = 22;
269
static final int FORCE_AUTO_ESCAPING_POLICY = 23;
270
271
// Template exception handler constants
272
static final TemplateExceptionHandler IGNORE_HANDLER;
273
static final TemplateExceptionHandler DEBUG_HANDLER;
274
static final TemplateExceptionHandler HTML_DEBUG_HANDLER;
275
static final TemplateExceptionHandler RETHROW_HANDLER;
276
```