Skip to content
Server Plugin

Pebble

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

代码示例: pebble

原生服务器Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。支持:✖️

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

添加依赖项 ​

要使用 Pebble,请将 ktor-server-pebble 工件添加到您的构建脚本中:

kotlin
implementation(ktorLibs.server.pebble)
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
groovy
implementation ktorLibs.server.pebble
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-pebble-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

安装 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 能够在相对于当前类路径的 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)))
}