Ktor 3.0.0-beta-2 Help

Pebble

Ktor allows you to use Pebble templates as views within your application by installing the Pebble plugin.

Add dependencies

To use Pebble, you need to include the ktor-server-pebble artifact in the build script:

implementation("io.ktor:ktor-server-pebble:$ktor_version")
implementation "io.ktor:ktor-server-pebble:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-pebble-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install Pebble

To install the Pebble plugin to the application, pass it to the install function in the specified module. The code snippets below show how to install Pebble...

  • ... inside the embeddedServer function call.

  • ... inside the explicitly defined module, which is an extension function of the Application class.

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) }
import io.ktor.server.application.* import io.ktor.server.pebble.* // ... fun Application.module() { install(Pebble) // ... }

Inside the install block, you can configure the PebbleEngine.Builder for loading Pebble templates.

Configure Pebble

Configure template loading

To load templates, you need to configure how to load templates using PebbleEngine.Builder. For example, the code snippet below enables Ktor to look up templates in the templates package relative to the current classpath:

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" }) } }

Send a template in response

Imagine you have the index.html template in resources/templates:

<html> <body> <h1>Hello, {{user.name}}</h1> </body> </html>

A data model for a user looks as follows:

data class User(val id: Int, val name: String)

To use the template for the specified route, pass PebbleContent to the call.respond method in the following way:

get("/index") { val sampleUser = User(1, "John") call.respond(PebbleContent("index.html", mapOf("user" to sampleUser))) }
Last modified: 02 April 2024