Main class for the execution of templates.
In order to execute Thymeleaf templates, an instance of this class (or one of its subclasses) must be created.
An instance of this class can be created at any time by calling its constructor:
final TemplateEngine templateEngine = new TemplateEngine();
Creation and configuration of TemplateEngine instances is expensive, so it is recommended to create only one instance of this class (or at least one instance per dialect/configuration) and use it to process multiple templates.
Once created, an instance of TemplateEngine has to be configured by setting the following required parameters:
Also, the following parameters can be optionally set:
All template executions require a context. A context is an object that implements the {@link IContext} interface, and that contains at least the followingdata:
Two {@link IContext} implementations are provided out-of-the-box:
Creating a {@link org.thymeleaf.context.Context} instance is very simple:
final IContext ctx = new Context();
ctx.setVariable("allItems", items);
A {@link org.thymeleaf.context.WebContext} would also need {@link javax.servlet.http.HttpServletRequest} and {@link javax.servlet.ServletContext} objects as constructor arguments:
final IContext ctx = new WebContext(request, servletContext);
ctx.setVariable("allItems", items);
See the documentation for these specific implementations for more details.
In order to execute templates, the {@link #process(String,IContext)} and{@link #process(String,IContext,Writer)} methods can be used:
Without a writer, the processing result will be returned as a String:
final String result = templateEngine.process("mytemplate", ctx);
By specifying a writer, we can avoid the creation of a String containing the whole processing result by writing this result into the output stream as soon as it is produced from the processed DOM. This is specially useful in web scenarios:
templateEngine.process("mytemplate", ctx, httpServletResponse.getWriter());
The "mytemplate" String argument is the template name, and it will relate to the physical/logical location of the template itself in a way configured at the template resolver/s.
@author Daniel Fernández @since 1.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|