Skip to content
Server Plugin

Pebble

必須の依存関係: io.ktor:ktor-server-pebble

コード例: pebble

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

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

依存関係の追加

Pebble を使用するには、ビルドスクリプトに ktor-server-pebble アーティファクトを含める必要があります。

Kotlin
Groovy
XML

Pebble のインストール

Pebble プラグインをアプリケーションにインストールするには、指定された

モジュール
モジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。
内の install 関数に渡します。 以下のコードスニペットは、Pebble をインストールする方法を示しています。

  • ... embeddedServer 関数の呼び出し内。
  • ... Application クラスの拡張関数である、明示的に定義された module 内。
kotlin
kotlin

install ブロック内では、Pebble テンプレートをロードするための PebbleEngine.Builder設定できます。

Pebble の設定

テンプレートのロード設定

テンプレートをロードするには、PebbleEngine.Builder を使用してテンプレートのロード方法を設定する必要があります。例えば、以下のコードスニペットは、Ktor が現在のクラスパスからの相対パスである templates パッケージ内でテンプレートを検索できるようにします。

kotlin
import io.ktor.server.application.*
import io.ktor.server.pebble.*
import io.ktor.server.response.*

fun Application.module() {
    install(Pebble) {
        loader(ClasspathLoader().apply {
            prefix = "templates"
        })
    }
}

レスポンスでのテンプレート送信

resources/templatesindex.html テンプレートがあると仮定します。

html
<html>
    <body>
        <h1>Hello, {{user.name}}</h1>
    </body>
</html>

ユーザーのデータモデルは以下の通りです。

kotlin
data class User(val id: Int, val name: String)

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

kotlin
get("/index") {
    val sampleUser = User(1, "John")
    call.respond(PebbleContent("index.html", mapOf("user" to sampleUser)))
}