Server Plugin
Pebble
所需依赖项:io.ktor:ktor-server-pebble
代码示例: pebble
原生服务器支持:✖️ Ktor 支持 Kotlin/Native,允许你在没有额外运行时或虚拟机的情况下运行服务器。
Ktor 允许你通过安装 Pebble 插件,在应用中使用 Pebble 模板 作为视图。
添加依赖项
要使用 Pebble,你需要在构建脚本中包含 ktor-server-pebble 构件:
Kotlin
Groovy
XML
安装 Pebble
要将 Pebble 插件安装到应用中,请将其传递给指定
模块
中的 模块允许你通过对路由进行分组来构建应用程序结构。
install 函数。 下面的代码片段展示了如何安装 Pebble ... - ... 在
embeddedServer函数调用内部。 - ... 在明确定义的
module内部,该模块是Application类的扩展函数。
kotlin
kotlin
在 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)))
}