Server Plugin
Thymeleaf
所需依赖项:io.ktor:ktor-server-thymeleaf
代码示例: thymeleaf
原生服务器 支持:✖️ Ktor 支持 Kotlin/Native,允许您在没有额外运行时或虚拟机的情况下运行服务器。
Ktor 允许您通过安装 Thymeleaf 插件,在应用程序中将 Thymeleaf 模板 用作视图。
添加依赖项
要使用 Thymeleaf,您需要在构建脚本中包含 ktor-server-thymeleaf 构件:
Kotlin
Groovy
XML
安装 Thymeleaf
要将 Thymeleaf 插件安装到应用程序中, 请将其传递给指定
模块
中的 模块允许您通过对路由进行分组来构建应用程序结构。
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。
