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 區塊內,您可以配置 MustacheFactory 以載入 Mustache 模板。

配置 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)))
}