Skip to content
Server Plugin

Pebble

必需的依賴項: io.ktor:ktor-server-pebble

程式碼範例: pebble

原生伺服器
模組允許您透過分組路由來組織應用程式。
支援: ✖️

Ktor 允許您透過安裝 Pebble 插件,將 Pebble 模板 作為您應用程式中的視圖使用。

加入依賴項

若要使用 Pebble,您需要將 ktor-server-pebble 構件包含在建置腳本中:

Kotlin
Groovy
XML

安裝 Pebble

若要將 Pebble 插件安裝至應用程式, 請在指定的

模組
模組允許您透過分組路由來組織應用程式。
中將其傳遞給 install 函數。 以下程式碼片段展示了如何安裝 Pebble ...

  • ...在 embeddedServer 函數呼叫內部。
  • ...在明確定義的 module 內部,此為 Application 類別的擴展函數。
kotlin
kotlin

install 區塊內部,您可以配置 PebbleEngine.Builder 以用於載入 Pebble 模板。

配置 Pebble

配置模板載入

若要載入模板,您需要配置如何使用 PebbleEngine.Builder 載入模板。例如,以下程式碼片段使 Ktor 能夠查找相對於當前 classpath 的 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)))
}