Skip to content
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 内部,后者是 Application 类的扩展函数。
kotlin
kotlin

配置 Thymeleaf

配置模板加载

install 代码块内部,你可以配置 ClassLoaderTemplateResolver。例如,下面的代码片段使 Ktor 能够在相对于当前 classpath 的 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