Server Plugin
Pebble
必要な依存関係: io.ktor:ktor-server-pebble
コード例: pebble
ネイティブサーバーKtorはKotlin/Nativeをサポートしており、追加のランタイムや仮想マシンなしでサーバーを実行できます。のサポート: ✖️
Ktorでは、Pebbleプラグインをインストールすることで、アプリケーション内のビューとしてPebbleテンプレートを使用できます。
依存関係の追加
Pebbleを使用するには、ビルドスクリプトにktor-server-pebbleアーティファクトを追加します:
kotlin
implementation(ktorLibs.server.pebble) 上記のコードスニペットでは、Ktorの依存関係を指定するために Ktorバージョンカタログを使用しています。
groovy
implementation ktorLibs.server.pebble 上記のコードスニペットでは、Ktorの依存関係を指定するために Ktorバージョンカタログを使用しています。
xml
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-pebble-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>Pebbleのインストール
アプリケーションにPebbleプラグインをインストールするには、 指定されたモジュールモジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。内のinstall関数に渡します。 以下の例は、Pebbleをインストールする方法を示しています:
embeddedServer()関数呼び出し内。Applicationクラスに明示的に定義されたmodule()拡張関数内。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.pebble.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(Pebble)
// ...
}.start(wait = true)
}kotlin
import io.ktor.server.application.*
import io.ktor.server.pebble.*
// ...
fun Application.module() {
install(Pebble)
// ...
}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/templatesにindex.htmlテンプレートがあると仮定します:
html
<html>
<body>
<h1>Hello, {{user.name}}</h1>
</body>
</html>ユーザーのデータモデルは以下のようになります:
kotlin
data class User(val id: Int, val name: String)指定されたルートでこのテンプレートを使用するには、次のようにPebbleContentをcall.respondメソッドに渡します:
kotlin
get("/index") {
val sampleUser = User(1, "John")
call.respond(PebbleContent("index.html", mapOf("user" to sampleUser)))
}