Thymeleaf
必要な依存関係: io.ktor:ktor-server-thymeleaf
コード例: thymeleaf
Native サーバーKtorはKotlin/Nativeをサポートしており、追加のランタイムや仮想マシンなしでサーバーを実行できます。のサポート: ✖️
Ktor では、Thymeleaf プラグインをインストールすることで、アプリケーション内で Thymeleaf テンプレート をビューとして使用できます。
依存関係の追加
Thymeleaf を使用するには、ビルドスクリプトに ktor-server-thymeleaf アーティファクトを追加します:
implementation(ktorLibs.server.thymeleaf)implementation ktorLibs.server.thymeleaf<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-thymeleaf-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>Thymeleaf のインストール
アプリケーションに Thymeleaf プラグインをインストールするには、指定されたモジュールモジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。内の install 関数に渡します。 以下の例は、Thymeleaf をインストールする方法を示しています:
embeddedServer()関数呼び出し内。Applicationクラスで明示的に定義されたmodule()拡張関数内。
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(Thymeleaf)
// ...
}.start(wait = true)
}import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
// ...
fun Application.module() {
install(Thymeleaf)
// ...
}Thymeleaf の設定
テンプレート読み込みの設定
install ブロック内で、ClassLoaderTemplateResolver を設定できます。例えば、以下のコードスニペットは、Ktor が現在のクラスパスを基準として templates パッケージ内の *.html テンプレートを検索できるようにします:
import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
fun Application.module() {
install(Thymeleaf) {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
prefix = "templates/"
suffix = ".html"
characterEncoding = "utf-8"
})
}
}レスポンスとしてテンプレートを送信する
resources/templates に index.html テンプレートがあるとします:
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="'Hello, ' + ${user.name}"></h1>
</body>
</html>ユーザーのデータモデルは以下のようになります:
data class User(val id: Int, val name: String)指定されたルートでテンプレートを使用するには、次のように ThymeleafContent を call.respond メソッドに渡します:
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}例: Thymeleaf テンプレートの自動リロード
以下の例は、開発モードが使用されているときに Thymeleaf テンプレートを自動的にリロードする方法を示しています。
package com.example
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.thymeleaf.*
import org.thymeleaf.templateresolver.*
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module() {
install(Thymeleaf) {
setTemplateResolver((if (developmentMode) {
FileTemplateResolver().apply {
cacheManager = null
prefix = "src/main/resources/templates/"
}
} else {
ClassLoaderTemplateResolver().apply {
prefix = "templates/"
}
}).apply {
suffix = ".html"
characterEncoding = "utf-8"
})
}
routing {
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}
}
}
data class User(val id: Int, val name: String)完全な例はこちらで確認できます: thymeleaf-auto-reload。
