Skip to content
Server Plugin

Thymeleaf

必要な依存関係: io.ktor:ktor-server-thymeleaf

コード例: thymeleaf

Native サーバーKtorはKotlin/Nativeをサポートしており、追加のランタイムや仮想マシンなしでサーバーを実行できます。のサポート: ✖️

Ktor では、Thymeleaf プラグインをインストールすることで、アプリケーション内で Thymeleaf テンプレート をビューとして使用できます。

依存関係の追加 ​

Thymeleaf を使用するには、ビルドスクリプトに ktor-server-thymeleaf アーティファクトを追加します:

kotlin
implementation(ktorLibs.server.thymeleaf)
上記のコードスニペットでは、Ktor の依存関係を指定するために Ktor バージョンカタログ を使用しています。
groovy
implementation ktorLibs.server.thymeleaf
上記のコードスニペットでは、Ktor の依存関係を指定するために Ktor バージョンカタログ を使用しています。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-thymeleaf-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

Thymeleaf のインストール ​

アプリケーションに Thymeleaf プラグインをインストールするには、指定されたモジュールモジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。内の install 関数に渡します。 以下の例は、Thymeleaf をインストールする方法を示しています:

  • embeddedServer() 関数呼び出し内。
  • Application クラスで明示的に定義された module() 拡張関数内。
kotlin
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)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
// ...
fun Application.module() {
    install(Thymeleaf)
    // ...
}

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)

指定されたルートでテンプレートを使用するには、次のように ThymeleafContent を call.respond メソッドに渡します:

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。