Skip to content
Server Plugin

Pebble

所需依赖项: io.ktor:ktor-server-pebble

代码示例: pebble

Native server
Ktor 支持 Kotlin/Native 并允许你运行一个无需额外运行时或虚拟机的服务器。
支持: ✖️

Ktor 允许你通过安装 Pebble 插件,在应用程序中将 Pebble 模板 用作视图。

添加依赖项

要使用 Pebble,你需要在构建脚本中包含 ktor-server-pebble artifact:

Kotlin
Groovy
XML

安装 Pebble

要将 Pebble 插件安装到应用程序中, 将其传递给指定

模块
模块允许你通过分组路由来组织应用程序。
中的 install 函数。 以下代码片段展示了如何安装 Pebble ...

  • ... 在 embeddedServer 函数调用内部。
  • ... 在显式定义的 module 内部,该模块是 Application 类的扩展函数。
kotlin
kotlin

install 代码块内部,你可以配置 PebbleEngine.Builder 以加载 Pebble 模板。

配置 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)))
}