Ktor 3.6.0 Help

Mustache

Ktor allows you to use Mustache templates as views within your application by installing the Mustache plugin.

Add dependencies

To use Mustache, add the ktor-server-mustache artifact to your build script:

implementation("io.ktor:ktor-server-mustache:$ktor_version")
implementation "io.ktor:ktor-server-mustache:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-mustache-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install Mustache

To install the Mustache plugin to your application, pass it to the install function in the specified module. The following examples show how to install Mustache:

  • In an embeddedServer() function call.

  • In an explicitly defined module() extension function on the Application class.

import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.application.* import io.ktor.server.mustache.* fun main() { embeddedServer(Netty, port = 8080) { install(Mustache) // ... }.start(wait = true) }
import io.ktor.server.application.* import io.ktor.server.mustache.* // ... fun Application.module() { install(Mustache) // ... }

Inside the install block, you can configure the MustacheFactory for loading Mustache templates.

Configure Mustache

Configure template loading

To load templates, you need to assign the MustacheFactory to the mustacheFactory property. For example, the code snippet below enables Ktor to look up templates in the templates package relative to the current classpath:

import com.github.mustachejava.DefaultMustacheFactory import io.ktor.server.application.* import io.ktor.server.mustache.Mustache import io.ktor.server.mustache.MustacheContent fun Application.module() { install(Mustache) { mustacheFactory = DefaultMustacheFactory("templates") } }

Send a template in response

Imagine you have the index.hbs template in resources/templates:

<html> <body> <h1>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 MustacheContent to the call.respond method in the following way:

get("/index") { val sampleUser = User(1, "John") call.respond(MustacheContent("index.hbs", mapOf("user" to sampleUser))) }
20 October 2025