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:
Gradle (Groovy)
Gradle (Kotlin)
Maven
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 …
import io.ktor.features.*
// ...
fun Application.main() {
install(Thymeleaf)
// ...
}
… or a specified module:
import io.ktor.features.*
// ...
fun Application.module() {
install(Thymeleaf)
// ...
}
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:
import io.ktor.thymeleaf.*
install(Thymeleaf) {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
prefix = "templates/"
suffix = ".html"
characterEncoding = "utf-8"
})
}
Send a Template in Response
Imagine you have the index.html
template in resources/templates
:
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="'Hello, ' + ${user.name}"></h1>
</body>
</html>
A data model for a user looks as follows:
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:
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}