LoginSignup
8
11

More than 5 years have passed since last update.

Thymeleaf with SpringBootで独自のUtilityを作る

Last updated at Posted at 2017-01-08

概要

YearMonthをサンプルに、独自のUtilityを作成する方法についてまとめる。
最終的に ${#yearmonths.format(hogeYm,'yyyy-MM')} で使えるようにする。

補足(追記)

Thymeleafにはデフォルトで日時APIを操作するUtilityが用意されていないので、サンプルにはYearMonthを利用しています。
ただし公式の追加モジュール(thymeleaf-extras-java8time)はあるようで、日時APIに関してはこちらを利用するほうがよさそうです。
ThymeleafとDate and Time API

前提

  • thymeleaf3
  • spring-boot 1.4

Utility本体の作成

実装はThymeleafのDatesを参考にしました。

public final class YearMonths {
    public String format(final YearMonth target, final String pattern) {
        if (target == null) {
            return null;
        }
        try {
            // org.thymeleaf.util.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);
        }
    }
}

独自Dialectの作成

日時Utilityを管理するDialectを作成します

public class YearMonthDialect implements IExpressionObjectDialect {
    // Thymeleafで使用したい名前
    private static final String YEAR_MONTH_EXPRESSION_NAME = "yearmonths";

    // 名前管理する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) {
                // 独自Utilityのインスタンスと名前を紐付け
                if(expressionObjectName.equals(YEAR_MONTH_EXPRESSION_NAME)){
                    return new YearMonths();
                }
                return null;
            }

            @Override
            public boolean isCacheable(String expressionObjectName) {
                // 必要に応じて実装
                return false;
            }
        };
    }

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

DIコンテナへの登録

SpringBootで利用可能にするには、DialectをDIコンテナへ登録しておく必要があります。
専用のConfigurationを作って登録しておく例を書いておきます。

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

テンプレートでの呼び出し

下記のように呼び出せるようになります。

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

まとめ

  1. Utilityを作成する
  2. Utilityを管理するDialectを作成する
  3. DialectをDIコンテナに登録する

参考

8
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
11