Server Plugin
JTE
安装 Jte 插件后,Ktor 允许您在应用中使用 JTE 模板 作为视图。
添加依赖项
要使用 Jte,您需要在构建脚本中包含 ktor-server-jte 工件:
Kotlin
Groovy
XML
要处理 .kte 文件,请将 gg.jte:jte-kotlin 工件添加到您的项目中:
Kotlin
Groovy
XML
当前的
jte‑kotlin编译器插件与 Kotlin 2.3.x 不兼容。 由于 Ktor 3.4.0 使用 Kotlin 2.3 工具链,在jte‑kotlin插件添加对 Kotlin 2.3 的支持之前,无法使用 Ktor JTE 插件。如果您依赖 JTE,请在
jte‑kotlin针对 Kotlin 2.3 更新之前使用 Kotlin 2.2.x 和兼容的 Ktor 版本。
安装 Jte
要在应用中安装 Jte 插件,请将其传递给指定
模块
中的 模块允许您通过对路由进行分组来构建应用。
install 函数。 以下代码片段展示了如何安装 Jte ... - ...在
embeddedServer函数调用中。 - ...在显式定义的
module中,它是Application类的一个扩展函数。
kotlin
kotlin
在 install 块中,您可以配置如何加载 JTE 模板。
配置 Jte
配置模板加载
要加载 JTE 模板,您需要:
- 创建一个用于解析模板代码的
CodeResolver。例如,您可以配置DirectoryCodeResolver从给定目录加载模板,或者配置ResourceCodeResolver从应用资源加载模板。 - 使用
templateEngine属性指定模板引擎,该引擎使用创建的CodeResolver将模板转换为原生 Java/Kotlin 代码。
例如,以下代码片段使 Ktor 能够在 templates 目录中查找 JTE 模板:
kotlin
import gg.jte.TemplateEngine
import gg.jte.resolve.DirectoryCodeResolver
import io.ktor.server.application.*
import io.ktor.server.jte.*
import java.nio.file.Path
fun Application.module() {
install(Jte) {
val resolver = DirectoryCodeResolver(Path.of("templates"))
templateEngine = TemplateEngine.create(resolver, gg.jte.ContentType.Html)
}
}在响应中发送模板
假设您在 templates 目录中有一个 index.kte 模板:
html
@param id: Int
@param name: String
<html>
<body>
<h1>Hello, ${name}!</h1>
</body>
</html>要为指定的路由使用该模板,请按以下方式将 JteContent 传递给 call.respond 方法:
kotlin
get("/index") {
val params = mapOf("id" to 1, "name" to "John")
call.respond(JteContent("index.kte", params))
}