Server Plugin
Thymeleaf
必要相依性:io.ktor:ktor-server-thymeleaf
程式碼範例: thymeleaf
原生伺服器 支援:✖️ Ktor supports Kotlin/Native and allows you to run a server without an additional runtime or virtual machine.
Ktor 允許您透過安裝 Thymeleaf 外掛程式,在應用程式中使用 Thymeleaf 範本 作為視圖(view)。
新增相依性
若要使用 Thymeleaf,您需要在組建指令碼中包含 ktor-server-thymeleaf 構件:
Kotlin
Groovy
XML
安裝 Thymeleaf
若要將 Thymeleaf 外掛程式安裝到應用程式中,請將其傳遞給指定
模組
中的 Modules allow you to structure your application by grouping routes.
install 函式。 下方的程式碼片段展示了如何安裝 Thymeleaf ... - ... 在
embeddedServer函式呼叫內。 - ... 在明確定義的
module內,該模組是Application類別的擴充方法。
kotlin
kotlin
配置 Thymeleaf
配置範本載入
在 install 區塊內,您可以配置 ClassLoaderTemplateResolver。例如,下方的程式碼片段讓 Ktor 能夠在相對於目前類別路徑的 templates 套件中尋找 *.html 範本:
kotlin
import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
fun Application.module() {
install(Thymeleaf) {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
prefix = "templates/"
suffix = ".html"
characterEncoding = "utf-8"
})
}
}在回應中傳送範本
假設您在 resources/templates 中有一個 index.html 範本:
html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="'Hello, ' + ${user.name}"></h1>
</body>
</html>使用者的資料模型如下所示:
kotlin
data class User(val id: Int, val name: String)若要為指定的路由使用範本,請按照以下方式將 ThymeleafContent 傳遞給 call.respond 方法:
kotlin
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}範例:自動重新載入 Thymeleaf 範本
下方的範例展示了在使用的開發模式下,如何自動重新載入 Thymeleaf 範本。
kotlin
package com.example
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.thymeleaf.*
import org.thymeleaf.templateresolver.*
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module() {
install(Thymeleaf) {
setTemplateResolver((if (developmentMode) {
FileTemplateResolver().apply {
cacheManager = null
prefix = "src/main/resources/templates/"
}
} else {
ClassLoaderTemplateResolver().apply {
prefix = "templates/"
}
}).apply {
suffix = ".html"
characterEncoding = "utf-8"
})
}
routing {
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}
}
}
data class User(val id: Int, val name: String)您可以在這裡找到完整的範例:thymeleaf-auto-reload。
