Package org.thymeleaf

Class TemplateEngine

  • All Implemented Interfaces:
    ITemplateEngine

    public class TemplateEngine
    extends Object
    implements ITemplateEngine

    Main class for the execution of templates.

    This is the only implementation of ITemplateEngine provided out of the box by Thymeleaf.

    Creating an instance of TemplateEngine

    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.

    Configuring the TemplateEngine

    Once created, an instance of TemplateEngine has to be typically configured a mechanism for resolving templates (i.e. obtaining and reading them):

    Templates will be processed according to a set of configured Dialects (implementations of IDialect), defining the way in which templates will be processed: processors, expression objects, etc. If no dialect is explicitly set, a unique instance of StandardDialect (the Standard Dialect) will be used.

    • Dialects define a default prefix, which will be used for them if not otherwise specified.
    • When setting/adding dialects, a non-default prefix can be specified for each of them.
    • Several dialects can use the same prefix, effectively acting as an aggregate dialect.

    Those templates that include any externalized messages (also internationalized messages, i18n) will need the TemplateEngine to be configured one or more Message Resolvers (implementations of IMessageResolver). If no message resolver is explicitly set, TemplateEngine will default 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.

    Also, building link URLs from templates will need the configuration of at least one link builder (implementation of ILinkBuilder) that will be in charge of giving shape to the URLs being output. If no link builder is explicitly set, a StandardLinkBuilder will be set as a default implementation, making use of the java Servlet API when it is needed for specific types of URLs.

    Besides these, a Cache Manager (implementation of ICacheManager) can also be configured. The Cache Manager is in charge of providing the cache objects (instances of ICache) to be used for caching (at least) parsed templates and parsed expressions. By default, a StandardCacheManager instance is used. If a null cache manager is specified by calling setCacheManager(ICacheManager), no caches will be used.

    Template Execution

    1. Creating a context

    All template executions require a context. A context is an object that implements the IContext interface, and that contains at least the following data:

    • The locale to be used for message externalization (internationalization).
    • The context variables. A map of variables that will be available for use from expressions in the executed template.

    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 access to request, session and servletcontext (application) attributes in special expression objects. Using an implementation of IWebContext is required when using Thymeleaf for generating HTML interfaces in web applications based on the Servlet API.

    Creating a Context instance is very simple:

    final Context ctx = new Context();
    ctx.setVariable("allItems", items);

    If you want, you can also specify the locale to be used for processing the template:

    final Context ctx = new Context(new Locale("gl","ES"));
    ctx.setVariable("allItems", items);

    A WebContext would also need HttpServletRequest, HttpServletResponse and ServletContext objects as constructor arguments:

    final WebContext ctx = new WebContext(request, response, servletContext);
    ctx.setVariable("allItems", items);

    See the documentation for these specific implementations for more details.

    2. Template Processing

    In order to execute templates, the different process(...) methods should be used. Those are mostly divided into two blocks: those that return the template processing result as a String, and those that receive a Writer as an argument and use it for writing the result instead.

    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 template. This is especially useful (and highly recommended) 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.


    Note a class with this name existed since 1.0, but it was completely reimplemented in Thymeleaf 3.0

    Since:
    3.0.0
    Author:
    Daniel Fernández
    • Field Detail

      • TIMER_LOGGER_NAME

        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.

    • Constructor Detail

      • TemplateEngine

        public TemplateEngine()

        Constructor for TemplateEngine objects.

        This is the only way to create a TemplateEngine instance (which should be configured after creation).

    • Method Detail

      • initializeSpecific

        protected void initializeSpecific()

        This method performs additional initializations required for a TemplateEngine subclass instance. This method is called before the first execution of process(String, org.thymeleaf.context.IContext) or processThrottled(String, org.thymeleaf.context.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.

        The base implementation of this method does nothing, and it is designed for being overridden by subclasses of TemplateEngine.

      • isInitialized

        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.

        Returns:
        true if the template engine has already been initialized, false if not.
      • getConfiguration

        public IEngineConfiguration getConfiguration()
        Description copied from interface: ITemplateEngine

        Obtain the IEngineConfiguration the template engine is using (or will be using) for processing templates.

        Note that calling this method on a TemplateEngine implementation will effectively initialize the engine object, and therefore any modifications to the configuration will be forbidden from that moment.

        Specified by:
        getConfiguration in interface ITemplateEngine
        Returns:
        the engine configuration object.
      • getDialectsByPrefix

        public final Map<String,Set<IDialect>> getDialectsByPrefix()

        Returns the configured dialects, referenced by their prefixes.

        Returns:
        the IDialect instances currently configured.
        Since:
        3.0.0
      • getDialects

        public final Set<IDialect> getDialects()

        Returns the configured dialects.

        Returns:
        the IDialect instances currently configured.
      • setDialect

        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.

        Parameters:
        dialect - the new unique IDialect to be used.
      • addDialect

        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.

        Parameters:
        prefix - the prefix that will be used for this dialect
        dialect - the new IDialect to be added to the existing ones.
      • addDialect

        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.

        Parameters:
        dialect - the new IDialect to be added to the existing ones.
      • setDialectsByPrefix

        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.

        Parameters:
        dialects - the new map of IDialect objects to be used, referenced by their prefixes.
      • setDialects

        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.

        Parameters:
        dialects - the new set of IDialect objects to be used.
      • setAdditionalDialects

        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.

        Parameters:
        additionalDialects - the new set of IDialect objects to be used.
        Since:
        2.0.9
      • clearDialects

        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.

      • getTemplateResolvers

        public final Set<ITemplateResolver> getTemplateResolvers()

        Returns the Set of template resolvers currently configured.

        Returns:
        the template resolvers.
      • setTemplateResolvers

        public void setTemplateResolvers(Set<ITemplateResolver> templateResolvers)

        Sets the entire set of template resolvers.

        Parameters:
        templateResolvers - the new template resolvers.
      • addTemplateResolver

        public void addTemplateResolver(ITemplateResolver templateResolver)

        Adds a new template resolver to the current set.

        Parameters:
        templateResolver - the new template resolver.
      • setTemplateResolver

        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.

        Parameters:
        templateResolver - the template resolver to be set.
      • getCacheManager

        public final 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.

        Returns:
        the cache manager
      • setCacheManager

        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.

        Parameters:
        cacheManager - the cache manager to be set.
      • getEngineContextFactory

        public final IEngineContextFactory getEngineContextFactory()

        Returns the engine context factory in effect. This factory is responsible for creating the (internally-used) instances of IEngineContext that will support template processing.

        By default, an instance of StandardEngineContextFactory is set.

        Returns:
        the cache manager
      • setEngineContextFactory

        public void setEngineContextFactory(IEngineContextFactory engineContextFactory)

        Sets the Engine Context Factory (implementation of IEngineContextFactory) to be used for template processing.

        By default, an instance of StandardEngineContextFactory 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.

        Parameters:
        engineContextFactory - the engine context factory to be used.
      • getDecoupledTemplateLogicResolver

        public final IDecoupledTemplateLogicResolver getDecoupledTemplateLogicResolver()

        Returns the Decoupled Template Logic Resolver in effect. This resolver is responsible for obtaining the resource containing the decoupled template logic to be added to templates that are marked during their own resolution to need additional external logic (in order for them to be pure HTML/XML markup).

        By default, an instance of StandardDecoupledTemplateLogicResolver is set.

        Returns:
        the decoupled template logic resolver
      • setDecoupledTemplateLogicResolver

        public void setDecoupledTemplateLogicResolver(IDecoupledTemplateLogicResolver decoupledTemplateLogicResolver)

        Sets the Decoupled Template Logic Resolver (implementation of IDecoupledTemplateLogicResolver) to be used for templates that require so.

        By default, an instance of StandardDecoupledTemplateLogicResolver 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.

        Parameters:
        decoupledTemplateLogicResolver - the engine context factory to be used.
      • getMessageResolvers

        public final Set<IMessageResolver> getMessageResolvers()

        Returns the set of Message Resolvers configured for this Template Engine.

        Returns:
        the set of message resolvers.
      • setMessageResolvers

        public void setMessageResolvers(Set<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.

        Parameters:
        messageResolvers - the Set of template resolvers.
      • addMessageResolver

        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.

        Parameters:
        messageResolver - the new message resolver to be added.
      • setMessageResolver

        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.

        Parameters:
        messageResolver - the message resolver to be set.
      • getLinkBuilders

        public final Set<ILinkBuilder> getLinkBuilders()

        Returns the set of Link Builders configured for this Template Engine.

        Returns:
        the set of link builders.
      • setLinkBuilders

        public void setLinkBuilders(Set<ILinkBuilder> linkBuilders)

        Sets the link builders 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.

        Parameters:
        linkBuilders - the Set of link builders.
      • addLinkBuilder

        public void addLinkBuilder(ILinkBuilder linkBuilder)

        Adds a link builder to the set of link builders 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.

        Parameters:
        linkBuilder - the new link builder to be added.
      • setLinkBuilder

        public void setLinkBuilder(ILinkBuilder linkBuilder)

        Sets a single link builder for this template engine.

        Calling this method is equivalent to calling setLinkBuilders(Set) passing a Set with only one link builder.

        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.

        Parameters:
        linkBuilder - the message resolver to be set.
      • clearTemplateCache

        public void clearTemplateCache()

        Completely clears the Template Cache.

        If this method is called before the TemplateEngine has been initialized, it causes its initialization.

      • clearTemplateCacheFor

        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.

        Parameters:
        templateName - the name of the template to be cleared from cache.
      • threadIndex

        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.

        Returns:
        the index of the current execution.
      • process

        public final String process(String template,
                                    IContext context)
        Description copied from interface: ITemplateEngine

        Process the specified template (usually the template name). Output will be written into a String that will be returned from calling this method, once template processing has finished.

        This is actually a convenience method that will internally create a TemplateSpec and then call ITemplateEngine.process(TemplateSpec, IContext).

        Specified by:
        process in interface ITemplateEngine
        Parameters:
        template - the template; depending on the template resolver this might be a template name or even the template contents (e.g. StringTemplateResolver).
        context - the context.
        Returns:
        a String containing the result of evaluating the specified template with the provided context.
      • process

        public final String process(String template,
                                    Set<String> templateSelectors,
                                    IContext context)
        Description copied from interface: ITemplateEngine

        Process the specified template (usually the template name) applying a set of template selectors. Output will be written into a String that will be returned from calling this method, once template processing has finished.

        Template selectors allow the possibility to process only a part of the specified template, expressing this selection in a syntax similar to jQuery, CSS or XPath selectors. Note this is only available for markup template modes (HTML, XML). For more info on template selectors syntax, have a look at AttoParser's markup selectors documentation.

        This is actually a convenience method that will internally create a TemplateSpec and then call ITemplateEngine.process(TemplateSpec, IContext).

        Specified by:
        process in interface ITemplateEngine
        Parameters:
        template - the template; depending on the template resolver this might be a template name or even the template contents (e.g. StringTemplateResolver).
        templateSelectors - the selectors to be used, defining the fragments that should be processed
        context - the context.
        Returns:
        a String containing the result of evaluating the specified template with the provided context.
      • process

        public final String process(TemplateSpec templateSpec,
                                    IContext context)
        Description copied from interface: ITemplateEngine

        Process a template starting from a TemplateSpec. Output will be written into a String that will be returned from calling this method, once template processing has finished.

        The template specification 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.

        Specified by:
        process in interface ITemplateEngine
        Parameters:
        templateSpec - the template spec containing the template to be resolved (usually its name only), template selectors if they are to be applied, a template mode if it should be forced (instead of computing it at resolution time), and other attributes.
        context - the context.
        Returns:
        a String containing the result of evaluating the specified template with the provided context.
      • process

        public final void process(String template,
                                  IContext context,
                                  Writer writer)
        Description copied from interface: ITemplateEngine

        Process the specified template (usually the template name). Output will be written to the specified writer as it is generated from processing the template. This is specially useful for web environments (using ServletResponse.getWriter()).

        This is actually a convenience method that will internally create a TemplateSpec and then call ITemplateEngine.process(TemplateSpec, IContext, Writer).

        Specified by:
        process in interface ITemplateEngine
        Parameters:
        template - the template; depending on the template resolver this might be a template name or even the template contents (e.g. StringTemplateResolver).
        context - the context.
        writer - the writer the results will be output to.
      • process

        public final void process(String template,
                                  Set<String> templateSelectors,
                                  IContext context,
                                  Writer writer)
        Description copied from interface: ITemplateEngine

        Process the specified template (usually the template name) applying a set of template selectors. Output will be written to the specified writer as it is generated from processing the template. This is specially useful for web environments (using ServletResponse.getWriter()).

        Template selectors allow the possibility to process only a part of the specified template, expressing this selection in a syntax similar to jQuery, CSS or XPath selectors. Note this is only available for markup template modes (HTML, XML). For more info on template selectors syntax, have a look at AttoParser's markup selectors documentation.

        This is actually a convenience method that will internally create a TemplateSpec and then call ITemplateEngine.process(TemplateSpec, IContext, Writer).

        Specified by:
        process in interface ITemplateEngine
        Parameters:
        template - the template; depending on the template resolver this might be a template name or even the template contents (e.g. StringTemplateResolver).
        templateSelectors - the selectors to be used, defining the fragments that should be processed. Can be null.
        context - the context.
        writer - the writer the results will be output to.
      • process

        public final void process(TemplateSpec templateSpec,
                                  IContext context,
                                  Writer writer)
        Description copied from interface: ITemplateEngine

        Process a template starting from a TemplateSpec. Output will be written to the specified writer as it is generated from processing the template. This is specially useful for web environments (using ServletResponse.getWriter()).

        The template specification 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.

        Specified by:
        process in interface ITemplateEngine
        Parameters:
        templateSpec - the template spec containing the template to be resolved (usually its name only), template selectors if they are to be applied, a template mode if it should be forced (instead of computing it at resolution time), and other attributes.
        context - the context.
        writer - the writer the results will be output to.
      • processThrottled

        public final IThrottledTemplateProcessor processThrottled(String template,
                                                                  IContext context)
        Description copied from interface: ITemplateEngine

        Process the specified template (usually the template name). Output will be generated from processing the template as dictated by the returned IThrottledTemplateProcessor, and will be written to the output means specified to this throttled processor's methods. This is specially useful for scenarios such as reactive architectures in which the production of output could be regulated by a back-pressure mechanism.

        This is actually a convenience method that will internally create a TemplateSpec and then call ITemplateEngine.process(TemplateSpec, IContext, Writer).

        Specified by:
        processThrottled in interface ITemplateEngine
        Parameters:
        template - the template; depending on the template resolver this might be a template name or even the template contents (e.g. StringTemplateResolver).
        context - the context.
        Returns:
        the IThrottledTemplateProcessor object in charge of dictating the engine when to process the template and how much output should be produced.
      • processThrottled

        public final IThrottledTemplateProcessor processThrottled(String template,
                                                                  Set<String> templateSelectors,
                                                                  IContext context)
        Description copied from interface: ITemplateEngine

        Process the specified template (usually the template name) applying a set of template selectors. Output will be generated from processing the template as dictated by the returned IThrottledTemplateProcessor, and will be written to the output means specified to this throttled processor's methods. This is specially useful for scenarios such as reactive architectures in which the production of output could be regulated by a back-pressure mechanism.

        Template selectors allow the possibility to process only a part of the specified template, expressing this selection in a syntax similar to jQuery, CSS or XPath selectors. Note this is only available for markup template modes (HTML, XML). For more info on template selectors syntax, have a look at AttoParser's markup selectors documentation.

        This is actually a convenience method that will internally create a TemplateSpec and then call ITemplateEngine.process(TemplateSpec, IContext, Writer).

        Specified by:
        processThrottled in interface ITemplateEngine
        Parameters:
        template - the template; depending on the template resolver this might be a template name or even the template contents (e.g. StringTemplateResolver).
        templateSelectors - the selectors to be used, defining the fragments that should be processed. Can be null.
        context - the context.
        Returns:
        the IThrottledTemplateProcessor object in charge of dictating the engine when to process the template and how much output should be produced.
      • processThrottled

        public final IThrottledTemplateProcessor processThrottled(TemplateSpec templateSpec,
                                                                  IContext context)
        Description copied from interface: ITemplateEngine

        Process a template starting from a TemplateSpec. Output will be generated from processing the template as dictated by the returned IThrottledTemplateProcessor, and will be written to the output means specified to this throttled processor's methods. This is specially useful for scenarios such as reactive architectures in which the production of output could be regulated by a back-pressure mechanism.

        The template specification 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.

        Specified by:
        processThrottled in interface ITemplateEngine
        Parameters:
        templateSpec - the template spec containing the template to be resolved (usually its name only), template selectors if they are to be applied, a template mode if it should be forced (instead of computing it at resolution time), and other attributes.
        context - the context.
        Returns:
        the IThrottledTemplateProcessor object in charge of dictating the engine when to process the template and how much output should be produced.