Using Pebble Templates

预计阅读时间: 2 分钟

Ktor includes support for Pebble templates through the PEbble feature. Initialize the Pebble feature with the PebbleEngine.Builder:

本特性在构件 io.ktor:ktor-pebble:$ktor_version 中的 io.ktor.pebble.Pebble 类中定义
dependencies { implementation "io.ktor:ktor-pebble:$ktor_version" }
dependencies { implementation("io.ktor:ktor-pebble:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-pebble</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Installation

You can install Pebble, and configure the PebbleEngine.Builder.

install(Pebble) { // this: PebbleEngine.Builder
    loader(ClasspathLoader().apply {
        prefix= 
    })
}

This loader will look for the template files on the classpath in the “templates” package.

Usage

A basic template looks like this:

<html>
<h2>Hello, {{ user.name }}!</h2>

Your email address is {{ user.email }}
</html>

With that template in resources/templates it is accessible elsewhere in the the application using the call.respond() method:

data class User(val name: String, val email: String)

get("/") {
    val user = User("user name", "[email protected]")
	 call.respond(PebbleContent("hello.html", mapOf("user" to user)))
}