Using Thymeleaf Templates
Ktor includes support for Thymeleaf templates through the Thymeleaffeature. Initialize the Thymeleaf feature with aClassLoaderTemplateResolver:
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:
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>
<!DOCTYPE html >
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span th:text="${user.name}"></span>
</body>
</html>
With that template in resources/templates
it is accessible elsewhere in the the applicationusing the call.respond()
method:
get("/") {
call.respond(ThymeleafContent("index", mapOf("user" to User(1, "user1"))))
}