Skip to content
Server Plugin

Mustache

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

代码示例 mustache

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

Ktor 允许您通过安装 Mustache 插件,在应用中将 Mustache 模板 用作视图。

添加依赖项

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

Kotlin
Groovy
XML

安装 Mustache

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

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

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

install 代码块中,您可以配置用于加载 Mustache 模板的 MustacheFactory

配置 Mustache

配置模板加载

要加载模板,您需要将 MustacheFactory 赋值给 mustacheFactory 属性。例如,以下代码段使 Ktor 能够在相对于当前类路径的 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)))
}