Skip to content
Server Plugin

Mustache

所需依赖项: io.ktor:ktor-server-mustache

代码示例: mustache

原生服务器
Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。
支持: ✖️

Ktor 允许您通过安装 Mustache 插件,在您的应用程序中使用 Mustache 模板 作为视图。

添加依赖项

要使用 Mustache,您需要在构建脚本中包含 ktor-server-mustache artifact:

Kotlin
Groovy
XML

安装 Mustache

安装 Mustache 插件到应用程序, 请将其传递给指定

模块
模块允许您通过对路由进行分组来构建应用程序。
中的 install 函数。 以下代码片段展示了如何安装 Mustache ...

  • ... 在 embeddedServer 函数调用内部。
  • ... 在显式定义的 module 内部,它是 Application 类的扩展函数。
kotlin
kotlin

install 代码块内部,您可以配置 MustacheFactory 以加载 Mustache 模板。

配置 Mustache

配置模板加载

要加载模板,您需要将 MustacheFactory 赋值给 mustacheFactory 属性。例如,以下代码片段使 Ktor 能够查找相对于当前 classpath 的 templates 包中的模板:

kotlin
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")
    }
}

在响应中发送模板

假设您在 resources/templates 中有一个 index.hbs 模板:

html
<html>
    <body>
        <h1>Hello, {{user.name}}</h1>
    </body>
</html>

用户的数据模型如下所示:

kotlin
data class User(val id: Int, val name: String)

要将模板用于指定的路由,请按以下方式将 MustacheContent 传递给 call.respond 方法:

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