しおしお

IntelliJ IDEAのことなんかを書いてます

Ktor 1.2.0(rc)で追加されたThymeleaf Featureを試してみた

KtorでThymeleafを試す - しおしおを書いたけど、Ktor 1.2.0(今はまだrc)からThymeleafが使えるようになるみたいなので試してみた。

gradle関連

gradle.properties

  • Ktorのバージョンを1.2.0系に設定する
ktor_version=1.2.0-rc2

build.gradle

  • ktor-thymeleaf をdependenciesに追加する
implementation "io.ktor:ktor-thymeleaf:$ktor_version"

サーバサイド

  • Thymeleaf をインストールする
  • installに渡すブロック内では、 Thymeleaf に関する設定を行う
    • この例では、クラスパス配下のテンプレートを使用する設定としている
  • respondには、viewでThymeleafが使われるようにするためにThymeleafContentを指定する
    • ThymeleafContentにはテンプレートの名前と、テンプレート内で使用するモデルを指定する
@Suppress("unused") // Referenced in application.conf
fun Application.module() {
    install(Thymeleaf) {
        setTemplateResolver(ClassLoaderTemplateResolver().apply { 
            prefix = "templates/"
            suffix = ".html"
            characterEncoding = "utf-8"
        })
    }

    routing {
        get("/") {
            call.respond(ThymeleafContent("test", mapOf("users" to Users(listOf(User(1, "user1"), User(2, "user2"))))))
        }
    }
}

class Users(private val users: List<User>) : Iterable<User> {
    override fun iterator(): Iterator<User> {
        return users.iterator()
    }

}

data class User(val id: Long, val name: String)

テンプレート

  • サーバサイドで設定したモデルの内容を表示するだけのシンプルなものにしています
<!DOCTYPE html >
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<ul>
  <!--/*@thymesVar id="users" type="siosio.Users"*/-->
  <!--/*@thymesVar id="user" type="siosio.User"*/-->
  <li th:each="user : ${users}" th:text="${user.id + ':' + user.name}"></li>
</ul>
</body>
</html>

実行結果

動きましたね。

f:id:sioiri:20190512072958p:plain