Using Pebble Templates

Estimated reading time: 1 minute

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

This feature is defined in the class io.ktor.pebble.Pebble in the artifact io.ktor:ktor-pebble:$ktor_version.
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", "user@example.com")
	 call.respond(PebbleContent("hello.html", mapOf("user" to user)))
}