Thymeleaf dialects are a set of features that allows you to extend default Thymeleaf engine functionality. Basic Thymeleaf dialect is called Standard Dialect, all common features come from it.
We can extend standard dialect with:
processing logic - processors that apply to attributes in Thymeleaf tags,
preprocessing and postprocessing logic - logic that can be applied before or after processing,
expression objects - used to perform the specialized operations in Thymeleaf expressions.
2. Maven dependencies
To show how Thymeleaf dialects works we used a sample Spring Boot application built as Maven project with the following dependencies:
Application is a main Spring Boot application class that starts the server,
WelcomeHeaderTagProcessor and WelcomeToAttributeTagProcessor are tag processors,
WelcomeDialect is a custom dialect that will extend Standard Thymeleaf Dialect,
IndexController handles GET requests to the root context,
index.html is a main Thymeleaf template where we use custom tag and attribute.
4. Extend Thymeleaf with custom dialect
This custom dialect will extend default one with two new processors:
WelcomeHeaderTagProcessor - this processor is creating custom header element,
WelcomeToAttributeTagProcessor - this processor is creating custom attribute.
4.1. Header tag processor
Let's check the implementation of the first processor, that extends AbstractElementTagProcessor, the base class to be used for tag processors that do not match on a specific attribute:
In WelcomeHeaderTagProcessor contructor we call base class contructor with the following parameters:
If dialectPrefix is fbe then we can create tag that will match with this specific processor like in the following example:
This code will be rendered to (how the processor will transform the HTML tag is provided in doProcess(...) method:
4.2. Welcome attribute tag processor
The attribute processor is implemented as a subclass of AbstractAttributeTagProcessor. This processor will be displaying the welcome message.
This processor will be triggered by a specific attribute.
will be rendered to
4.3. Dialect class
To register our processors we need to create the Dialect class that extends an abstract class called AbstractProcessorDialect. This class has the following structure:
Note that the dialect class should be annotated with Spring @Component in order to tell the Spring framework that it should be processed. We register processors attached to this dialect in the getProcessors(...) method.
Now, let's check sample Thymeleaf template that used custom tags and attributes:
5. Conclusion
This article presents how to extend Thymeleaf Standard Dialect with new processors for custom tags and attributes.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}