Mustache
Ktor allows you to use Mustache templates as views within your application by installing the Mustache feature.
Add Dependencies
To enable Mustache
support, you need to include the ktor-mustache
artifact in the build script:
Gradle (Groovy)
Gradle (Kotlin)
Maven
implementation "io.ktor:ktor-mustache:$ktor_version"
Install Mustache
To install the Mustache
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(Mustache)
// ...
}
… or a specified module:
import io.ktor.features.*
// ...
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 io.ktor.mustache.*
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)))
}