Using Mustache Templates

预计阅读时间: 2 分钟

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:

本特性在构件 io.ktor:ktor-mustache:$ktor_version 中的 io.ktor.mustache.Mustache 类中定义
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)))
}