Server Plugin
Pebble
必要相依性: io.ktor:ktor-server-pebble
程式碼範例: pebble
原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。 支援: ✖️
Ktor 允許您透過安裝 Pebble 外掛程式,在應用程式中使用 Pebble 範本 作為檢視 (views)。
新增相依性
若要使用 Pebble,請將 ktor-server-pebble 構件新增至您的建置指令碼中:
安裝 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 能夠相對於目前的類別路徑 (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)))
}