Using Freemarker Templates

Ktor includes support for FreeMarker templates through the FreeMarkerfeature. Initialize the FreeMarker feature with aTemplateLoader:

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

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:

This feature is defined in the class io.ktor.freemarker.FreeMarker in the artifact io.ktor:ktor-freemarker:$ktor_version.

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>

  1. <html>
  2. <h2>Hello ${user.name}!</h2>
  3. Your email address is ${user.email}
  4. </html>

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

  1. get("/{...}") {
  2. val user = User("user name", "user@example.com")
  3. call.respond(FreeMarkerContent("index.ftl", mapOf("user" to user), "e"))
  4. }