Ratpack入門シリーズ
- Ratpack入門 (1) - Ratpackとは
- Ratpack入門 (2) - アーキテクチャー
- Ratpack入門 (3) - hello world 詳解
- Ratpack入門 (4) - ルーティング & 静的コンテンツ
- Ratpack入門 (5) - Json & Registry
- Ratpack入門 (6) - Promise
- Ratpack入門 (7) - Guice & Spring
- Ratpack入門 (8) - セッション
- Ratpack入門 (9) - Thymeleaf
Thymeleaf
Ratpackは、Thymeleafテンプレートエンジンをサポートするモジュールを提供しています。
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" ) );
} );
};
第一引数のマップがパラメーターのバインディング、第二引数がテンプレートの名前です。BaseDirがpublic/.ratpackとすると、実際に解決されるファイルは、public/thymeleaf/template.htmlになります。
テンプレートファイルは、通常のThymeleafと全く同じです。
<!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以降で公式が対応しました。そちらをお使いください。