Using YearMonth as a sample, I will summarize how to create your own Utility.
Finally, make it available in $ {# yearmonths.format (hogeYm,'yyyy-MM')}
.
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
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 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";
}
}
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();
}
}
You will be able to call it as follows.
${#yearmonths.format(hogeYm,'yyyy-MM')}
-Try Thymeleaf 3.0 Part 3 Make a utility -Create a Utility Object (original View Helper in Rails) with thymeleaf
Recommended Posts