public class TemplateEngine extends Object
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:
ITemplateResolver
), in
charge of reading or obtaining the templates so that the engine is able to process them. If
only one template resolver is set (the most common case), the setTemplateResolver(ITemplateResolver)
method can be used for this. If more resolvers are to be set, both the
setTemplateResolvers(Set)
and addTemplateResolver(ITemplateResolver)
methods
can be used.Also, the following parameters can be optionally set:
IDialect
), defining the way in which templates
will be processed: DOM processors, expression parsers, etc. If no
dialect is explicitly set, a unique instance of StandardDialect
(the Standard Dialect) will be used.
IMessageResolver
), in
charge of resolving externalized messages. If no message resolver is explicitly set, the default
setting specified by setDefaultMessageResolvers(Set)
will be applied (this
default setting defaults itself to a single instance of StandardMessageResolver
).
If only one message resolver is set, the setMessageResolver(IMessageResolver)
method
can be used for this. If more resolvers are to be set, both the
setMessageResolvers(Set)
and addMessageResolver(IMessageResolver)
methods
can be used.ITemplateModeHandler
, which will
take care of reading/parsing templates and also writing the results of processing them for a
specific template mode. The presence of these template mode handlers defines which are the valid
values for the templateMode attribute of template resolution results
(TemplateResolution.getTemplateMode()
). If not explicitly set, template mode handlers
will be initialized to StandardTemplateModeHandlers.ALL_TEMPLATE_MODE_HANDLERS
.
ICacheManager
. The Cache Manager is in charge of
providing the cache objects (instances of ICache
) to be used for
caching (at least) templates, fragments, messages and expressions. By default, a
StandardCacheManager
instance is used. If a null cache manager is specified by calling
setCacheManager(ICacheManager)
, no caches will be used throughout the system at all.
All template executions require a context. A context is an object that
implements the IContext
interface, and that contains at least the following
data:
Two IContext
implementations are provided out-of-the-box:
Context
, a standard implementation containing only
the required data.WebContext
, a web-specific implementation
extending the IWebContext
subinterface, offering
request, session and servletcontext (application) attributes in special variables
inside the context variables map. Using an implementation of
IWebContext
is required when using Thymeleaf for
generating HTML/XHTML interfaces in web applications.
Creating a Context
instance is very simple:
final Context ctx = new Context();
ctx.setVariable("allItems", items);
A WebContext
would also need
HttpServletRequest
and
ServletContext
objects as constructor arguments:
final Context 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 process(String, IContext)
and
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.
Modifier and Type | Field and Description |
---|---|
static String |
TIMER_LOGGER_NAME
Name of the TIMER logger.
|
Constructor and Description |
---|
TemplateEngine()
Constructor for TemplateEngine objects.
|
Modifier and Type | Method and Description |
---|---|
void |
addDialect(IDialect dialect)
Adds a new dialect for this template engine, using the dialect's specified
default dialect.
|
void |
addDialect(String prefix,
IDialect dialect)
Adds a new dialect for this template engine, using the specified prefix.
|
void |
addMessageResolver(IMessageResolver messageResolver)
Adds a message resolver to the set of message resolvers to be used
by the template engine.
|
void |
addTemplateModeHandler(ITemplateModeHandler templateModeHandler)
Adds a Template Mode Handler to the set of Template Mode Handlers to be used
by the template engine.
|
void |
addTemplateResolver(ITemplateResolver templateResolver)
Adds a new template resolver to the current set.
|
void |
clearDialects()
Removes all the currently configured dialects.
|
void |
clearTemplateCache()
Completely clears the Template Cache.
|
void |
clearTemplateCacheFor(String templateName)
Clears the entry in the Template Cache for the specified
template, if it is currently cached.
|
ICacheManager |
getCacheManager()
Returns the cache manager in effect.
|
Configuration |
getConfiguration()
Returns the configuration object.
|
Set<IDialect> |
getDialects()
Returns the configured dialects.
|
Map<String,IDialect> |
getDialectsByPrefix()
Returns the configured dialects, referenced by their prefixes.
|
Set<IMessageResolver> |
getMessageResolvers()
Returns the set of Message Resolvers configured for this Template Engine.
|
Set<ITemplateModeHandler> |
getTemplateModeHandlers()
Returns the set of Template Mode Handlers configured for this
Template Engine.
|
TemplateRepository |
getTemplateRepository()
Returns the template repository.
|
Set<ITemplateResolver> |
getTemplateResolvers()
Returns the Set of template resolvers currently configured.
|
void |
initialize()
Internal method that initializes the Template Engine instance.
|
protected void |
initializeSpecific()
This method performs additional initializations required for a
TemplateEngine.
|
boolean |
isInitialized()
Checks whether the TemplateEngine has already been initialized
or not.
|
String |
process(String templateName,
IContext context)
Process a template.
|
String |
process(String templateName,
IContext context,
IFragmentSpec fragmentSpec)
Process a template.
|
void |
process(String templateName,
IContext context,
IFragmentSpec fragmentSpec,
Writer writer)
Process a template.
|
void |
process(String templateName,
IContext context,
Writer writer)
Process a template.
|
void |
process(String templateName,
IProcessingContext processingContext,
IFragmentSpec fragmentSpec,
Writer writer)
Process a template.
|
void |
process(String templateName,
IProcessingContext processingContext,
Writer writer)
Process a template.
|
void |
setAdditionalDialects(Set<IDialect> additionalDialects)
Sets an additional set of dialects for this template engine, all of them using
their default prefixes.
|
void |
setCacheManager(ICacheManager cacheManager)
Sets the Cache Manager to be used.
|
void |
setDefaultMessageResolvers(Set<? extends IMessageResolver> defaultMessageResolvers)
Sets the default message resolvers.
|
void |
setDefaultTemplateModeHandlers(Set<? extends ITemplateModeHandler> defaultTemplateModeHandlers)
Sets the default Template Mode Handlers.
|
void |
setDialect(IDialect dialect)
Sets a new unique dialect for this template engine.
|
void |
setDialects(Set<IDialect> dialects)
Sets a new set of dialects for this template engine, all of them using
their default prefixes.
|
void |
setDialectsByPrefix(Map<String,IDialect> dialects)
Sets a new set of dialects for this template engine, referenced
by the prefixes they will be using.
|
void |
setMessageResolver(IMessageResolver messageResolver)
Sets a single message resolver for this template engine.
|
void |
setMessageResolvers(Set<? extends IMessageResolver> messageResolvers)
Sets the message resolvers to be used by this template engine.
|
void |
setTemplateModeHandlers(Set<? extends ITemplateModeHandler> templateModeHandlers)
Sets the Template Mode Handlers to be used by this template engine.
|
void |
setTemplateResolver(ITemplateResolver templateResolver)
Sets a single template resolver for this template engine.
|
void |
setTemplateResolvers(Set<? extends ITemplateResolver> templateResolvers)
Sets the entire set of template resolvers.
|
static String |
threadIndex()
Internal method that retrieves the thread name/index for the
current template execution.
|
public static final String TIMER_LOGGER_NAME
Name of the TIMER logger. This logger will output the time required for executing each template processing operation.
The value of this constant is org.thymeleaf.TemplateEngine.TIMER. This allows you to set a specific configuration and/or appenders for timing info at your logging system configuration.
public TemplateEngine()
Constructor for TemplateEngine objects.
This is the only way to create a TemplateEngine instance (which should be configured after creation).
public final boolean isInitialized()
Checks whether the TemplateEngine has already been initialized
or not. A TemplateEngine is initialized when the initialize()
method is called the first time a template is processed.
Normally, there is no good reason why users would need to call this method.
public Configuration getConfiguration()
Returns the configuration object.
public TemplateRepository getTemplateRepository()
Returns the template repository. Normally there is no reason why users would want to obtain or use this object directly (and it is not recommended behaviour).
public final Map<String,IDialect> getDialectsByPrefix()
Returns the configured dialects, referenced by their prefixes.
IDialect
instances currently configured.public final Set<IDialect> getDialects()
Returns the configured dialects.
IDialect
instances currently configured.public void setDialect(IDialect dialect)
Sets a new unique dialect for this template engine.
This operation is equivalent to removing all the currently configured dialects and then adding this one.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
dialect
- the new unique IDialect
to be used.public void addDialect(String prefix, IDialect dialect)
Adds a new dialect for this template engine, using the specified prefix.
This dialect will be added to the set of currently configured ones.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
prefix
- the prefix that will be used for this dialectdialect
- the new IDialect
to be added to the existing ones.public void addDialect(IDialect dialect)
Adds a new dialect for this template engine, using the dialect's specified default dialect.
This dialect will be added to the set of currently configured ones.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
dialect
- the new IDialect
to be added to the existing ones.public void setDialectsByPrefix(Map<String,IDialect> dialects)
Sets a new set of dialects for this template engine, referenced by the prefixes they will be using.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
dialects
- the new map of IDialect
objects to be used, referenced
by their prefixes.public void setDialects(Set<IDialect> dialects)
Sets a new set of dialects for this template engine, all of them using their default prefixes.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
dialects
- the new set of IDialect
objects to be used.public void setAdditionalDialects(Set<IDialect> additionalDialects)
Sets an additional set of dialects for this template engine, all of them using their default prefixes.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
additionalDialects
- the new set of IDialect
objects to be used.public void clearDialects()
Removes all the currently configured dialects.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
public final Set<ITemplateResolver> getTemplateResolvers()
Returns the Set of template resolvers currently configured.
public void setTemplateResolvers(Set<? extends ITemplateResolver> templateResolvers)
Sets the entire set of template resolvers.
templateResolvers
- the new template resolvers.public void addTemplateResolver(ITemplateResolver templateResolver)
Adds a new template resolver to the current set.
templateResolver
- the new template resolver.public void setTemplateResolver(ITemplateResolver templateResolver)
Sets a single template resolver for this template engine.
Calling this method is equivalent to calling setTemplateResolvers(Set)
passing a Set with only one template resolver.
templateResolver
- the template resolver to be set.public ICacheManager getCacheManager()
Returns the cache manager in effect. This manager is in charge of providing the various caches needed by the system during its process.
By default, an instance of StandardCacheManager
is set.
public void setCacheManager(ICacheManager cacheManager)
Sets the Cache Manager to be used. If set to null, no caches will be used throughout the engine.
By default, an instance of StandardCacheManager
is set.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
cacheManager
- the cache manager to be set.public final Set<IMessageResolver> getMessageResolvers()
Returns the set of Message Resolvers configured for this Template Engine.
public void setMessageResolvers(Set<? extends IMessageResolver> messageResolvers)
Sets the message resolvers to be used by this template engine.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
messageResolvers
- the Set of template resolvers.public void addMessageResolver(IMessageResolver messageResolver)
Adds a message resolver to the set of message resolvers to be used by the template engine.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
messageResolver
- the new message resolver to be added.public void setMessageResolver(IMessageResolver messageResolver)
Sets a single message resolver for this template engine.
Calling this method is equivalent to calling setMessageResolvers(Set)
passing a Set with only one message resolver.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
messageResolver
- the message resolver to be set.public void setDefaultMessageResolvers(Set<? extends IMessageResolver> defaultMessageResolvers)
Sets the default message resolvers. These are used when no message resolvers
are set via the setMessageResolver(IMessageResolver)
,
setMessageResolvers(Set)
or addMessageResolver(IMessageResolver)
methods.
This method is useful for creating subclasses of TemplateEngine that establish default configurations for message resolvers.
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
defaultMessageResolvers
- the default message resolvers.public final Set<ITemplateModeHandler> getTemplateModeHandlers()
Returns the set of Template Mode Handlers configured for this Template Engine.
By default, template mode handlers set are
StandardTemplateModeHandlers.ALL_TEMPLATE_MODE_HANDLERS
public void setTemplateModeHandlers(Set<? extends ITemplateModeHandler> templateModeHandlers)
Sets the Template Mode Handlers to be used by this template engine. Every available template mode must have its corresponding handler.
By default, template mode handlers set are
StandardTemplateModeHandlers.ALL_TEMPLATE_MODE_HANDLERS
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
templateModeHandlers
- the Set of Template Mode Handlers.public void addTemplateModeHandler(ITemplateModeHandler templateModeHandler)
Adds a Template Mode Handler to the set of Template Mode Handlers to be used by the template engine. Every available template mode must have its corresponding handler.
By default, template mode handlers set are
StandardTemplateModeHandlers.ALL_TEMPLATE_MODE_HANDLERS
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
templateModeHandler
- the new Template Mode Handler to be added.public void setDefaultTemplateModeHandlers(Set<? extends ITemplateModeHandler> defaultTemplateModeHandlers)
Sets the default Template Mode Handlers. These are used when no Template Mode Handlers
are set via the setTemplateModeHandlers(Set)
or
addTemplateModeHandler(ITemplateModeHandler)
methods.
This method is useful for creating subclasses of TemplateEngine that establish default configurations for Template Mode Handlers.
By default, template mode handlers set are
StandardTemplateModeHandlers.ALL_TEMPLATE_MODE_HANDLERS
This operation can only be executed before processing templates for the first time. Once a template is processed, the template engine is considered to be initialized, and from then on any attempt to change its configuration will result in an exception.
defaultTemplateModeHandlers
- the default Template Mode Handlers.public void clearTemplateCache()
Completely clears the Template Cache.
If this method is called before the TemplateEngine has been initialized, it causes its initialization.
public void clearTemplateCacheFor(String templateName)
Clears the entry in the Template Cache for the specified template, if it is currently cached.
If this method is called before the TemplateEngine has been initialized, it causes its initialization.
templateName
- the name of the template to be cleared from cache.public final void initialize()
Internal method that initializes the Template Engine instance. This method
is called before the first execution of process(String, IContext)
in order to create all the structures required for a quick execution of
templates.
THIS METHOD IS INTERNAL AND SHOULD NEVER BE CALLED DIRECTLY.
If a subclass of TemplateEngine needs additional steps for
initialization, the initializeSpecific()
method should
be overridden.
protected void initializeSpecific()
This method performs additional initializations required for a
TemplateEngine. It is called by initialize()
.
The implementation of this method does nothing, and it is designed for being overridden by subclasses of TemplateEngine.
public static String threadIndex()
Internal method that retrieves the thread name/index for the current template execution.
THIS METHOD IS INTERNAL AND SHOULD NEVER BE CALLED DIRECTLY.
public final String process(String templateName, IContext context)
Process a template. This method receives both a template name and a context.
The template name will be used as input for the template resolvers, queried in chain until one of them resolves the template, which will then be executed.
The context will contain the variables that will be available for the execution of expressions inside the template.
templateName
- the name of the template.context
- the context.public final String process(String templateName, IContext context, IFragmentSpec fragmentSpec)
Process a template. This method receives both a template name, a context
and a fragment specification (IFragmentSpec
). This
method works essentially the same as process(String, IContext)
but
applying the specified fragment specification as a filter on the parsed template in order to
process only a fragment of such template.
templateName
- the name of the template.context
- the context.fragmentSpec
- the fragment specification that will be applied as a filter to the parsed
template, before processing.public final void process(String templateName, IContext context, Writer writer)
Process a template. This method receives a template name, a context and
also a Writer
, so that there is no need to create a String object containing the
whole processing results because these will be written to the specified writer as
soon as they are generated from the processed DOM tree. This is specially useful for
web environments (using ServletResponse.getWriter()
).
The template name will be used as input for the template resolvers, queried in chain until one of them resolves the template, which will then be executed.
The context will contain the variables that will be available for the execution of expressions inside the template.
templateName
- the name of the template.context
- the context.writer
- the writer the results will be output to.public final void process(String templateName, IProcessingContext processingContext, Writer writer)
Process a template. This method receives a template name, a processing context
(which might include local variables) and also a Writer
, so that there is no need
to create a String object containing the whole processing results because these will be
written to the specified writer as soon as they are generated from the processed DOM
tree. This is specially useful for web environments
(using ServletResponse.getWriter()
).
The template name will be used as input for the template resolvers, queried in chain until one of them resolves the template, which will then be executed.
The context will contain the variables that will be available for the execution of expressions inside the template.
templateName
- the name of the template.processingContext
- the processing context.writer
- the writer the results will be output to.public final void process(String templateName, IContext context, IFragmentSpec fragmentSpec, Writer writer)
Process a template. This method receives a template name, a context, a
fragment specification (IFragmentSpec
) and also a Writer
. This
method works essentially the same as process(String, IContext, Writer)
but
applying the specified fragment specification as a filter on the parsed template in order to
process only a fragment of such template.
templateName
- the name of the template.context
- the context.fragmentSpec
- the fragment specification that will be applied as a filter to the parsed
template, before processing.writer
- the writer the results will be output to.public final void process(String templateName, IProcessingContext processingContext, IFragmentSpec fragmentSpec, Writer writer)
Process a template. This method receives a template name, a processing context
(which might include local variables), a fragment specification (IFragmentSpec
)
and also a Writer
. This method works essentially the same as
process(String, IContext, Writer)
but applying the specified fragment specification
as a filter on the parsed template in order to process only a fragment of such template.
templateName
- the name of the template.processingContext
- the processing context.fragmentSpec
- the fragment specification that will be applied as a filter to the parsed
template, before processing.writer
- the writer the results will be output to.Copyright © 2017 The THYMELEAF team. All rights reserved.