DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Momento Migrates Object Cache as a Service to Ampere® Altra®
  • Why I Ditched Redis for Cloudflare Durable Objects in My Rate Limiter
  • Real-Object Detection at the Edge: AWS IoT Greengrass and YOLOv5
  • Monitoring and Managing the Growth of the MSDB System Database in SQL Server

Trending

  • When Snowflake Lies to You: Understanding False Failures in dbt Pipelines
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • 5 Failure Patterns That Break AI Chatbots in Production
  • Rethinking Java CRUDs With Event Sourcing and CQRS Patterns
  1. DZone
  2. Coding
  3. Languages
  4. Creating an Expression Object Using Thymeleaf

Creating an Expression Object Using Thymeleaf

In this article, see how to create Thymeleaf functions like #string, #dates, #lists.

By 
Jerffeson Gomes user avatar
Jerffeson Gomes
·
Updated Sep. 17, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
13.6K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

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.

Maven Dependencies

First, let's add our Thymeleaf dependency to the pom.xml file:

XML
 




x


 
1
<dependency>
2
 
          
3
        <groupId>nz.net.ultraq.thymeleaf</groupId>
4
 
          
5
        <artifactId>thymeleaf-layout-dialect</artifactId>
6
 
          
7
</dependency>



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.

Java
 




xxxxxxxxxx
1
12


 
1
public final class NumberUtils {
2
  
3
    public String isEven(Integer number) {
4
        if (number % 2 == 0) {
5
            return number +" is even";
6
        } else {
7
            return number + " is not even";
8
        }
9
    }
10
}
11
 
          



Factory Class

This class is responsible for generating our utils object and will return it to the thymeleaf template engine.

Java
x
 
1
public class NumberExpressionFactory implements IExpressionObjectFactory {
2
 
          
3
    private static final String TEMPORAL_EVALUATION_VARIABLE_NAME = "number";
4
    
5
    private static final Set<String> ALL_EXPRESSION_OBJECT_NAMES = Collections.unmodifiableSet(
6
            new HashSet<>(Arrays.asList(TEMPORAL_EVALUATION_VARIABLE_NAME)));
7
    
8
    @Override
9
    public Set<String> getAllExpressionObjectNames() {
10
        return ALL_EXPRESSION_OBJECT_NAMES;
11
    }
12
 
          
13
    @Override
14
    public Object buildObject(
15
IExpressionContext context, String expressionObjectName) {
16
        if (
17
TEMPORAL_EVALUATION_VARIABLE_NAME.equals(expressionObjectName)) {
18
            return new NumberUtils();
19
        }
20
        return null;
21
    }
22
 
          
23
    @Override
24
    public boolean isCacheable(String expressionObjectName) {
25
        return true;
26
    }
27
 
          
28
}
29
 
          


In the 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.

Dialect Class

This class implements an AbstractDialect and 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.

Java
 




xxxxxxxxxx
1
14


 
1
public class NumberExpressionDialect extends AbstractDialect implements IExpressionObjectDialect {
2
 
          
3
    private final IExpressionObjectFactory NUMBER_EXPRESSION_OBJECTS_FACTORY = new NumberExpresseionFactory();
4
    
5
    public NumberExpressionDialect() {
6
        super("number");
7
    }
8
 
          
9
    @Override
10
    public IExpressionObjectFactory getExpressionObjectFactory() {
11
        return PAPEL_EXPRESSION_OBJECTS_FACTORY;
12
    }
13
}
14
 
          



In getExpressionObjectFactory() we return an object of type  IExpressionObjectFactory  (Just the type of our NumberExpressionFactory).

Creating MvcConfig

In this file, we will configure all the dialects used by the thymeleaf template engine.

Java
 




xxxxxxxxxx
1
34


 
1
@Configuration
2
public class MvcConfig implements WebMvcConfigurer {
3
 
          
4
  
5
    @Bean
6
    @Description("Thymeleaf template resolver serving HTML 5")
7
    public ClassLoaderTemplateResolver templateResolver() {
8
        
9
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
10
        
11
        templateResolver.setPrefix("templates/");
12
        templateResolver.setCacheable(false);
13
        templateResolver.setSuffix(".html");       
14
        templateResolver.setCharacterEncoding("UTF-8");
15
       
16
        return templateResolver;
17
    }
18
  
19
  
20
    @Bean
21
    @Description("Thymeleaf template engine with Spring integration")
22
    public SpringTemplateEngine templateEngine() {
23
        
24
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
25
        templateEngine.setTemplateResolver(templateResolver());
26
 
          
27
        templateEngine.addDialect(new NumberExpressionDialect());
28
        
29
        return templateEngine;
30
    }
31
    
32
 
          
33
}
34
 
          



First, we define our template to resolve and in the next method we add our dialect to the templateEngine of thymeleaf.

The HTML

Just use our dialect and expression like the others

HTML
 




xxxxxxxxxx
1


 
1
<div th:text=”${#number.isEven(10)}”></div>



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.

Thymeleaf Object (computer science) Dialect (computing)

Opinions expressed by DZone contributors are their own.

Related

  • Momento Migrates Object Cache as a Service to Ampere® Altra®
  • Why I Ditched Redis for Cloudflare Durable Objects in My Rate Limiter
  • Real-Object Detection at the Edge: AWS IoT Greengrass and YOLOv5
  • Monitoring and Managing the Growth of the MSDB System Database in SQL Server

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook