Using Freemarker Templates

预计阅读时间: 2 分钟

Ktor includes support for FreeMarker templates through the FreeMarker feature. Initialize the FreeMarker feature with a TemplateLoader:

    install(FreeMarker) {
        templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
    }

This TemplateLoader sets up FreeMarker to look for the template files on the classpath in the “templates” package, relative to the current class path. A basic template looks like this:

本特性在构件 io.ktor:ktor-freemarker:$ktor_version 中的 io.ktor.freemarker.FreeMarker 类中定义
dependencies { implementation "io.ktor:ktor-freemarker:$ktor_version" }
dependencies { implementation("io.ktor:ktor-freemarker:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-freemarker</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>
<html>
<h2>Hello ${user.name}!</h2>

Your email address is ${user.email}
</html>

With that template in resources/templates it is accessible elsewhere in the the application using the call.respond() method:

data class User(val name: String, val email: String)

get("/") {
	val user = User("user name", "[email protected]")
	call.respond(FreeMarkerContent("hello.ftl", mapOf("user" to user)))
}