Using Thymeleaf Templates

Ktor includes support for Thymeleaf templates through the Thymeleaffeature. Initialize the Thymeleaf feature with aClassLoaderTemplateResolver:

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

This TemplateResolver sets up Thymeleaf to look for the template files on the classpath in the“templates” package, relative to the current class path. A basic template looks like this:

This feature is defined in the class io.ktor.thymeleaf.Thymeleaf in the artifact io.ktor:ktor-thymeleaf:$ktor_version.

dependencies { implementation "io.ktor:ktor-thymeleaf:$ktor_version"}

dependencies { implementation("io.ktor:ktor-thymeleaf:$ktor_version")}

<project> … <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-thymeleaf</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies></project>

  1. <!DOCTYPE html >
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <span th:text="${user.name}"></span>
  9. </body>
  10. </html>

With that template in resources/templates it is accessible elsewhere in the the applicationusing the call.respond() method:

  1. get("/") {
  2. call.respond(ThymeleafContent("index", mapOf("user" to User(1, "user1"))))
  3. }