Server Plugin
Thymeleaf
所需依赖项: io.ktor:ktor-server-thymeleaf
代码示例: thymeleaf
原生服务器Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。支持: ✖️
Ktor 允许你通过安装 Thymeleaf 插件,在应用程序中使用 Thymeleaf 模板作为视图。
添加依赖项
要使用 Thymeleaf,请将 ktor-server-thymeleaf 工件添加到你的构建脚本中:
安装 Thymeleaf
要在应用程序中安装 Thymeleaf 插件, 请将其传递给指定模块模块允许您通过对路由进行分组来构建应用程序结构。中的 install 函数。 以下示例展示了如何安装 Thymeleaf:
- 在
embeddedServer()函数调用中。 - 在
Application类上显式定义的module()扩展函数中。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(Thymeleaf)
// ...
}.start(wait = true)
}kotlin
import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
// ...
fun Application.module() {
install(Thymeleaf)
// ...
}配置 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。
