Ktor 1.6.8 Help

Thymeleaf

Ktor allows you to use Thymeleaf templates as views within your application by installing the Thymeleaf plugin (previously known as feature).

Add dependencies

To enable Thymeleaf support, you need to include the ktor-thymeleaf artifact in the build script:

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

Install Thymeleaf

To install the Thymeleaf plugin, pass it to the install function in the application initialization code. Depending on the way used to create a server, this can be the embeddedServer function call ...

import io.ktor.features.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(Thymeleaf) // ... }.start(wait = true) }

... or a specified module.

import io.ktor.features.* // ... fun Application.module() { install(Thymeleaf) // ... }

Configure Thymeleaf

Configure template loading

Inside the install block, you can configure the ClassLoaderTemplateResolver. For example, the code snippet below enables Ktor to look up *.html templates in the templates package relative to the current classpath:

install(Thymeleaf) { setTemplateResolver(ClassLoaderTemplateResolver().apply { prefix = "templates/" suffix = ".html" characterEncoding = "utf-8" }) }

Send a template in response

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

<html xmlns:th="http://www.thymeleaf.org"> <body> <h1 th:text="'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 ThymeleafContent to the call.respond method in the following way:

get("/index") { val sampleUser = User(1, "John") call.respond(ThymeleafContent("index", mapOf("user" to sampleUser))) }
Last modified: 28 May 2021