Thymeleaf

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:

Thymeleaf - 图1

Gradle (Groovy)

Gradle (Kotlin)

Maven

Thymeleaf - 图2

  1. implementation "io.ktor:ktor-thymeleaf:$ktor_version"

Install Thymeleaf

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

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.main() {
  4. install(Thymeleaf)
  5. // ...
  6. }

… or a specified module:

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.module() {
  4. install(Thymeleaf)
  5. // ...
  6. }

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:

  1. import io.ktor.thymeleaf.*
  2. install(Thymeleaf) {
  3. setTemplateResolver(ClassLoaderTemplateResolver().apply {
  4. prefix = "templates/"
  5. suffix = ".html"
  6. characterEncoding = "utf-8"
  7. })
  8. }

Send a Template in Response

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

  1. <html xmlns:th="http://www.thymeleaf.org">
  2. <body>
  3. <h1 th:text="'Hello, ' + ${user.name}"></h1>
  4. </body>
  5. </html>

A data model for a user looks as follows:

  1. 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:

  1. get("/index") {
  2. val sampleUser = User(1, "John")
  3. call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
  4. }