Skip to content
Server Plugin

Mustache

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

代码示例: mustache

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

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

添加依赖项 ​

要使用 Mustache,请将 ktor-server-mustache 工件添加到构建脚本中:

kotlin
implementation(ktorLibs.server.mustache)
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
groovy
implementation ktorLibs.server.mustache
上述代码段使用 Ktor 版本目录来指定 Ktor 依赖项。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-mustache-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

安装 Mustache ​

要将 Mustache 插件安装到应用程序中,请在指定的模块模块允许您通过对路由进行分组来构建应用程序结构。中将其传递给 install 函数。 以下示例展示了如何安装 Mustache:

  • 在 embeddedServer() 函数调用中。
  • 在 Application 类上显式定义的 module() 扩展函数中。
kotlin
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)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.mustache.*
// ...
fun Application.module() {
    install(Mustache)
    // ...
}

在 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)))
}