Using Mustache Templates

Ktor includes support for Mustache templates through the Mustachefeature. Initialize the Mustache feature with aMustacheFactory:

  1. install(Mustache) {
  2. mustacheFactory = DefaultMustacheFactory("templates")
  3. }

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>

  1. <html>
  2. <h1>Hello </h1>
  3. </html>

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

  1. get("/{...}") {
  2. val user = User("user name", "user@example.com")
  3. call.respond(MustacheContent("todos.hbs", mapOf("user" to user)))
  4. }