Skip to content
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/templatesindex.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