FreeMarker

Ktor allows you to use FreeMarker templates as views within your application by installing the Freemarker feature.

Add Dependencies

To enable FreeMarker support, you need to include the ktor-freemarker artifact in the build script:

FreeMarker - 图1

Gradle (Groovy)

Gradle (Kotlin)

Maven

FreeMarker - 图2

  1. implementation "io.ktor:ktor-freemarker:$ktor_version"

Install FreeMarker

To install the FreeMarker feature, pass it to the install function in the application initialization code. This can be the main function …

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.main() {
  4. install(FreeMarker)
  5. // ...
  6. }

… or a specified module:

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.module() {
  4. install(FreeMarker)
  5. // ...
  6. }

Inside the install block, you can configure the desired TemplateLoader for loading FreeMarker templates.

Configure FreeMarker

Configure Template Loading

To load templates, you need to assign the desired TemplateLoader type to the templateLoader property. For example, the code snippet below enables Ktor to look up templates in the templates package relative to the current classpath:

  1. import io.ktor.freemarker.*
  2. install(FreeMarker) {
  3. templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
  4. }

Send a Template in Response

Imagine you have the index.ftl template in resources/templates:

  1. <html>
  2. <body>
  3. <h1>Hello, ${user.name}!</h1>
  4. </body>
  5. </html>

A data model for a user looks as follows:

  1. data class User(val id: Int, val name: String)

To use the template for the specified route, pass FreeMarkerContent to the call.respond method in the following way:

  1. get("/index") {
  2. val sampleUser = User(1, "John")
  3. call.respond(FreeMarkerContent("index.ftl", mapOf("user" to sampleUser)))
  4. }