Creating an Expression Object Using Thymeleaf
In this article, see how to create Thymeleaf functions like #string, #dates, #lists.
Join the DZone community and get the full member experience.Join For Free
In this tutorial, we will learn how to create an Expression object (similar to #string, #dates, #lists), using Thymeleaf. It will check whether a number is even or odd. For this, let's use a quick and practical example.
What Is a Thymeleaf Dialect?
A dialect allows you to add custom functionality to thymeleaf. Thus extending your ability to build and reuse templates.
First, let's add our Thymeleaf dependency to the
This dependency will allow us to use the standard thymeleaf dialect.
Creating Our Dialect
The creation of our dialect goes through the creation of 3 classes: Utils, Factory and Dialect.
Number Utils Class
The Utils class will contain all of our business logic. It is in this class where all of our Java code will stay.
This class is responsible for generating our utils object and will return it to the thymeleaf template engine.
EVALUATION_VARIABLE_NAME variable we define the name of the dialect that will be used to generate an object from our NumberUtils class. In the
buildObject method we make a comparison to find out if the dialect to be executed corresponds to that of our factory.
This class implements an
IExpressionObjectDialect and will be the definition of our dialect.
The first represents an abstract dialect and the second an expression object. With that, thymeleaf will recognize our class as a new dialect that can be used in the processing of templetes. Like the representation of a new expression object.
We created an object from our factory and in the builder, we passed the name of our dialect to thymeleaf. This is the name that will be provided in the
buildObject method of the factory class.
getExpressionObjectFactory() we return an object of type
IExpressionObjectFactory (Just the type of our
In this file, we will configure all the dialects used by the thymeleaf template engine.
First, we define our template to resolve and in the next method we add our dialect to the templateEngine of thymeleaf.
Just use our dialect and expression like the others
You can find the complete source code for this article on this GitHub repository, and please feel free to provide your valuable feedback in the comments section.
Opinions expressed by DZone contributors are their own.