LoginSignup
1
1

More than 3 years have passed since last update.

Ratpack入門 (9) - Thymeleaf

Last updated at Posted at 2018-02-09

Ratpack入門シリーズ

  1. Ratpack入門 (1) - Ratpackとは
  2. Ratpack入門 (2) - アーキテクチャー
  3. Ratpack入門 (3) - hello world 詳解
  4. Ratpack入門 (4) - ルーティング & 静的コンテンツ
  5. Ratpack入門 (5) - Json & Registry
  6. Ratpack入門 (6) - Promise
  7. Ratpack入門 (7) - Guice & Spring
  8. Ratpack入門 (8) - セッション
  9. Ratpack入門 (9) - Thymeleaf

Thymeleaf

Ratpackは、Thymeleafテンプレートエンジンをサポートするモジュールを提供しています。

build.gradle
dependencies {
    compile "io.ratpack:ratpack-thymeleaf:${ratpack}"
}

モジュールを追加します。

Function<Registry, Registry> registry = ratpack.guice.Guice.registry( bindings -> {
    bindings.module( new ThymeleafModule() );
} );

Thymeleafモジュールは、デフォルトで${BaseDir}/thymeleaf以下の*.htmlファイルをテンプレートとして認識します。そのためBaseDirの設定が必須です。

ServerConfig.builder()
            .development( true )
            .findBaseDir( "public/.ratpack" )

この場合、public/thymeleafがテンプレートディレクトリとみなされます。

モジュールはratpack.thymeleaf.Templateクラス用のRendererを登録します。ThymeleafのIContext用のレンダラーではないことに注意してください。Templateは、Template.thymeleafTemplate()メソッドから作成できます。

Action<Chain> handlers = chain -> {
    chain.get( "/:name?", ctx -> {
        String name = ctx.getPathTokens().get( "name" );
        name = name.isEmpty() ? "world" : name;
        ctx.render( Template.thymeleafTemplate( ImmutableMap.of( "name", name ), "template" ) );
    } );
};

第一引数のマップがパラメーターのバインディング、第二引数がテンプレートの名前です。BaseDirpublic/.ratpackとすると、実際に解決されるファイルは、public/thymeleaf/template.htmlになります。

テンプレートファイルは、通常のThymeleafと全く同じです。

template.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta content="text/html; charset=UTF-8" />
</head>

<body>
<h1 th:text="'hello, ' + ${name}"></h1>
</body>

</html>

このように、Thymeleafの使い方は非常に簡単です。モジュールの実装自体も、テンプレートを表すクラスと、テンプレートエンジンをラップするレンダラーの実装があればいいため、簡単に作ることができます。同様のパターンで、Velocityやほかのテンプレートエンジンに対応することも、容易に出来るかと思います。

Thymeleafのバージョンについて

Ratpack公式が提供しているモジュールは現在(2018年2月)、Thymeleaf 2.1.5までです。バージョン3には対応しません(仕方がないので私は自分で実装しました - 宣伝)。
1.6.0以降で公式が対応しました。そちらをお使いください。

1
1
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
1
1