Server Plugin
Pebble
必要相依性:io.ktor:ktor-server-pebble
程式碼範例: pebble
原生伺服器 支援:✖️ Ktor supports Kotlin/Native and allows you to run a server without an additional runtime or virtual machine.
Ktor 允許您透過安裝 Pebble 外掛程式,在應用程式中將 Pebble 範本作為視圖使用。
新增相依性
要使用 Pebble,您需要在建置指令碼中包含 ktor-server-pebble 構件:
Kotlin
Groovy
XML
安裝 Pebble
要將 Pebble 外掛程式安裝到應用程式中, 請將其傳遞給指定
模組
中的 Modules allow you to structure your application by grouping routes.
install 函式。 下方的程式碼片段展示了如何安裝 Pebble ... - ... 在
embeddedServer函式呼叫內。 - ... 在明確定義的
module內,該模組是Application類別的擴充函式。
kotlin
kotlin
在 install 區塊內,您可以設定用於載入 Pebble 範本的 PebbleEngine.Builder。
設定 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)))
}