Using Mustache Templates
Ktor includes support for Mustache templates through the Mustachefeature. Initialize the Mustache feature with aMustacheFactory:
install(Mustache) {
mustacheFactory = DefaultMustacheFactory("templates")
}
This MustacheFactory sets up Mustache 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.mustache.Mustache
in the artifact io.ktor:ktor-mustache:$ktor_version
.
dependencies { implementation "io.ktor:ktor-mustache:$ktor_version"}
dependencies { implementation("io.ktor:ktor-mustache:$ktor_version")}
<project> … <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-mustache</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies></project>
<html>
<h1>Hello </h1>
</html>
With that template in resources/templates
it is accessible elsewhere in the the applicationusing the call.respond()
method:
get("/{...}") {
val user = User("user name", "user@example.com")
call.respond(MustacheContent("todos.hbs", mapOf("user" to user)))
}