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関数の呼び出し内。
  • ... Applicationクラスの拡張関数である、明示的に定義されたmodule内。
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