Using Mustache Templates

Estimated reading time: 1 minute

Ktor includes support for Mustache templates through the Mustache feature. Initialize the Mustache feature with a MustacheFactory:

    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 {{ user.name }}</h1>

Your email address is {{ user.email }}
</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", "user@example.com")
    call.respond(MustacheContent("hello.hbs", mapOf("user" to user)))
}