Using Thymeleaf Templates

预计阅读时间:1分钟

Ktor通过Thymeleaf功能支持Thymeleaf模板. 使用ClassLoaderTemplateResolver初始化Thymeleaf功能:

    install(Thymeleaf) {
        setTemplateResolver(ClassLoaderTemplateResolver().apply { 
            prefix = "templates/"
            suffix = ".html"
            characterEncoding = "utf-8"
        })
    }

此TemplateResolver设置Thymeleaf,以在"模板"包中相对于当前类路径的类路径上查找模板文件. 基本模板如下所示:

此功能定义在类io.ktor.thymeleaf.Thymeleaf在神器io.ktor:ktor-thymeleaf:$ktor_version .
dependencies { implementation "io.ktor:ktor-thymeleaf:$ktor_version" }
dependencies { implementation("io.ktor:ktor-thymeleaf:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-thymeleaf</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>
<!DOCTYPE html >
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<span th:text="${user.name}"></span>
</body>
</html>

使用resources/templates ,可以使用call.respond()方法在应用程序的其他位置访问该模板:

    get("/") {
        call.respond(ThymeleafContent("index", mapOf("user" to User(1, "user1"))))
    }

by  ICOPY.SITE