Using Thymeleaf Templates

预计阅读时间: 2 分钟

Ktor includes support for Thymeleaf templates through the Thymeleaf feature. Initialize the Thymeleaf feature with a ClassLoaderTemplateResolver:

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

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:

本特性在构件 io.ktor:ktor-thymeleaf:$ktor_version 中的 io.ktor.thymeleaf.Thymeleaf 类中定义
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>
<!DOCTYPE html >
<html xmlns:th="">
  <meta charset="UTF-8">
<span th:text="${}"></span>

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

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