Skip to content
Server Plugin

Mustache

必要的相依性io.ktor:ktor-server-mustache

程式碼範例 mustache

原生伺服器
Ktor 支援 Kotlin/Native,允許您在沒有額外執行階段或虛擬機的情況下執行伺服器。
支援:✖️

Ktor 允許您透過安裝 Mustache 外掛程式,在應用程式中將 Mustache 範本 用作視圖 (view)。

新增相依性

若要使用 Mustache,您需要在組建指令碼中包含 ktor-server-mustache 構件:

Kotlin
Groovy
XML

安裝 Mustache

若要將 Mustache 外掛程式安裝到應用程式中,請將其傳遞給指定

模組
模組允許您透過將路由分組來建構應用程式。
中的 install 函式。 下方的程式碼片段展示了如何安裝 Mustache ...

  • ... 在 embeddedServer 函式呼叫內。
  • ... 在明確定義的 module 內,該模組是 Application 類別的擴充函式。
kotlin
kotlin

install 區塊內,您可以設定用於載入 Mustache 範本的 MustacheFactory

設定 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)))
}