Server Plugin
Thymeleaf
所需依賴項:io.ktor:ktor-server-thymeleaf
程式碼範例: thymeleaf
原生伺服器支援:✖️ Ktor 支援 Kotlin/Native,並允許您在沒有額外運行時或虛擬機器的情況下運行伺服器。
Ktor 允許您透過安裝 Thymeleaf 插件,在您的應用程式中使用 Thymeleaf 模板作為視圖。
新增依賴項
要使用 Thymeleaf
,您需要在構建腳本中包含 ktor-server-thymeleaf
artifact:
Kotlin
Groovy
XML
安裝 Thymeleaf
要將 Thymeleaf
插件安裝到應用程式中, 請在指定的
模組
中將其傳遞給 模組允許您透過分組路由來組織應用程式。
install
函數。 下面的程式碼片段顯示了如何安裝 Thymeleaf
... - ... 在
embeddedServer
函數呼叫內部。 - ... 在顯式定義的
module
內部,該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。