Server Plugin
Thymeleaf
必須の依存関係: io.ktor:ktor-server-thymeleaf
コード例: thymeleaf
ネイティブサーバーのサポート: ✖️ KtorはKotlin/Nativeをサポートしており、追加のランタイムや仮想マシンなしでサーバーを実行できます。
Ktorでは、Thymeleafプラグインをインストールすることで、アプリケーション内でThymeleafテンプレートをビューとして使用できます。
依存関係の追加
Thymeleaf
を使用するには、ktor-server-thymeleaf
アーティファクトをビルドスクリプトに含める必要があります。
Kotlin
Groovy
XML
Thymeleafのインストール
アプリケーションにThymeleaf
プラグインをインストールするには、 指定された
モジュール
内のモジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。
install
関数に渡します。 以下のコードスニペットは、Thymeleaf
をインストールする方法を示しています... - ...
embeddedServer
関数呼び出し内で。 - ... 明示的に定義された
module
内 (Application
クラスの拡張関数)。
kotlin
kotlin
Thymeleafの設定
テンプレートの読み込み設定
install
ブロック内で、ClassLoaderTemplateResolver
を設定できます。例えば、以下のコードスニペットは、Ktorが現在のクラスパスに対するtemplates
パッケージ内の*.html
テンプレートを探せるようにします。
kotlin
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
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="'Hello, ' + ${user.name}"></h1>
</body>
</html>
ユーザーのデータモデルは以下のようになります。
kotlin
data class User(val id: Int, val name: String)
指定されたルートでテンプレートを使用するには、call.respond
メソッドにThymeleafContentを以下のように渡します。
kotlin
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}
例: Thymeleafテンプレートの自動リロード
以下の例は、開発モードが使用されている場合にThymeleafテンプレートを自動的にリロードする方法を示しています。
kotlin
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。