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="http://www.thymeleaf.org">
<body>
<h2 th:text="'Hello ' + ${user.name} + '!'"></h2>
<p>Your email address is <span th:text="${user.email}"></span></p>
</body>
</html>

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

data class User(val name: String, val email: String)

get("/") {
    val user = User("user name", "[email protected]")
    call.respond(ThymeleafContent("hello", mapOf("user" to user)))
    }