Ktor 1.5.4 Help


Ktor allows you to use Thymeleaf templates as views within your application by installing the Thymeleaf 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"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-thymeleaf</artifactId> <version>${ktor_version}</version> </dependency>

Install Thymeleaf

To install the Thymeleaf feature, pass it to the install function in the application initialization code. This can be the main function ...

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

... 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: 19 April 2021