KtorはThymeleafテンプレートをThymeleaf Featureを通じてサポートしています。 ClassLoaderTemplateResolverとともにThymeleaf Featureを初期化します:
install(Thymeleaf) {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
prefix = "templates/"
suffix = ".html"
characterEncoding = "utf-8"
})
}
このTemplateLoaderは、Thymeleafがテンプレートファイルをクラスパス上で現在のクラスパスからの相対パスとして”templates”パッケージ内で見つけられるようにセットアップします。 基本的なテンプレートは以下のような見た目になります:
io.ktor.thymeleaf.Thymeleaf
in the artifact 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">
<body>
<h2 th:text="'Hello ' + ${user.name} + '!'"></h2>
<p>Your email address is <span th:text="${user.email}"></span></p>
</body>
</html>
アプリケーション内のどこででもcall.respond()
メソッドを利用することで、このresources/templates
のテンプレートにアクセスできます。
data class User(val name: String, val email: String)
get("/") {
val user = User("user name", "user@example.com")
call.respond(ThymeleafContent("hello", mapOf("user" to user)))
}