Create your own Utility with Thymeleaf with Spring Boot

Overview

Using YearMonth as a sample, I will summarize how to create your own Utility. Finally, make it available in $ {# yearmonths.format (hogeYm,'yyyy-MM')}.

Supplement (additional note)

Since Thymeleaf does not have a Utility to operate the date and time API by default, YearMonth is used for the sample. However, there seems to be an official additional module (thymeleaf-extras-java8time), and it seems better to use this for the date and time API. Thymeleaf and Date and Time API

Premise

Creating the Utility body

The implementation was based on Thymeleaf's Dates.

public final class YearMonths {
    public String format(final YearMonth target, final String pattern) {
        if (target == null) {
            return null;
        }
        try {
            // org.thymeleaf.util.Use Validate
            Validate.notEmpty(pattern, "Pattern cannot be null or empty");
            return target.format(DateTimeFormatter.ofPattern(pattern));
        } catch (final Exception e) {
            throw new TemplateProcessingException(
                    "Error formatting date with format pattern \"" + pattern + "\"", e);
        }
    }
}

Create your own Dialect

Create a Dialect to manage the date and time Utility

public class YearMonthDialect implements IExpressionObjectDialect {
    //The name you want to use in Thymeleaf
    private static final String YEAR_MONTH_EXPRESSION_NAME = "yearmonths";

    //Name management Set
    private static final Set<String> ALL_EXPRESSION_NAMES = new HashSet<String>(){
                {add(YEAR_MONTH_EXPRESSION_NAME);}
            };

    @Override
    public IExpressionObjectFactory getExpressionObjectFactory() {
        return new IExpressionObjectFactory() {
            @Override
            public Set<String> getAllExpressionObjectNames() {
                return ALL_EXPRESSION_NAMES;
            }

            @Override
            public Object buildObject(IExpressionContext context, String expressionObjectName) {
                //Associate the name with the instance of your own Utility
                if(expressionObjectName.equals(YEAR_MONTH_EXPRESSION_NAME)){
                    return new YearMonths();
                }
                return null;
            }

            @Override
            public boolean isCacheable(String expressionObjectName) {
                //Implemented as needed
                return false;
            }
        };
    }

    @Override
    public String getName() {
        return "YearMonth";
    }
}

Registration to DI container

Dialect must be registered in the DI container to be available in SpringBoot. I will write an example of creating and registering a dedicated Configuration.

@Configuration
public class ThymeleafConfiguration {
    @Bean
    public DateTimeDialect DateTimeDialect() {
        return new DateTimeDialect();
    }
}

Call in template

You will be able to call it as follows.

${#yearmonths.format(hogeYm,'yyyy-MM')}

Summary

  1. Create a Utility
  2. Create a Dialect to manage the Utility
  3. Register Dialect in DI container

reference

-Try Thymeleaf 3.0 Part 3 Make a utility -Create a Utility Object (original View Helper in Rails) with thymeleaf

Recommended Posts

Create your own Utility with Thymeleaf with Spring Boot
How to create your own Controller corresponding to / error with Spring Boot
Create CRUD apps with Spring Boot 2 + Thymeleaf + MyBatis
Create microservices with Spring Boot
Create your own validator with Bean Validation
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Implement paging function with Spring Boot + Thymeleaf
Run WEB application with Spring Boot + Thymeleaf
Create a website with Spring Boot + Gradle (jdk1.8.x)
Create a simple search app with Spring Boot
Add your own authentication items with Spring Security
Create Spring Boot environment with Windows + VS Code
Create a web api server with spring boot
Download with Spring Boot
Create a Spring Boot development environment with docker
Create Spring Cloud Config Server with security with Spring Boot 2.0
Create Restapi with Spring Boot ((1) Until Run of App)
Create a simple demo site with Spring Security with Spring Boot 2.1
Call your own method with PreAuthorize in Spring Security
Generate barcode with Spring Boot
Hello World with Spring Boot
Get started with Spring boot
Hello World with Spring Boot!
Run LIFF with Spring Boot
SNS login with Spring Boot
[Java] Thymeleaf Basic (Spring Boot)
Create your own Java annotations
Spring Boot starting with Docker
Hello World with Spring Boot
Set cookies with Spring Boot
Use Spring JDBC with Spring Boot
Add module with Spring Boot
Getting Started with Spring Boot
Send email with spring boot
Handle Java 8 date and time API with Thymeleaf with Spring Boot
Until INSERT and SELECT to Postgres with Spring boot and thymeleaf
Use thymeleaf3 with parent without specifying spring-boot-starter-parent in Spring Boot
Use Basic Authentication with Spring Boot
Make your own sampler with JMeter
gRPC on Spring Boot with grpc-spring-boot-starter
Hot deploy with Spring Boot development
Create your own Solr Function Query
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Inquiry application creation with Spring Boot
Get validation results with Spring Boot
(Intellij) Hello World with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Check date correlation with Spring Boot
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
Create your own encode for String.getBytes ()
Beginning with Spring Boot 0. Use Spring CLI
I tried Flyway with Spring Boot
Authentication / authorization with Spring Security & Thymeleaf
Thymeleaf usage notes in Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Processing at application startup with Spring Boot
How to apply thymeleaf changes to the browser immediately with #Spring Boot + maven
Create Spring Boot development environment on Vagrant