Server Plugin
Mustache
必要相依性:io.ktor:ktor-server-mustache
程式碼範例: mustache
原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。支援:✖️
Ktor 允許你藉由安裝 Mustache 外掛程式,在應用程式中使用 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 在相對於當前 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)))
}