Ktor 2.1.1 Help

FreeMarker

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

Add dependencies

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

implementation("io.ktor:ktor-server-freemarker:$ktor_version")
implementation "io.ktor:ktor-server-freemarker:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-freemarker-jvm</artifactId> <version>${ktor_version}</version> </dependency>

Install FreeMarker

To install the FreeMarker plugin, pass it to the install function in the application initialization code. Depending on the way used to create a server, this can be the embeddedServer function call ...

import io.ktor.server.application.* import io.ktor.server.freemarker.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(FreeMarker) // ... }.start(wait = true) }

... or a specified module.

import io.ktor.server.application.* import io.ktor.server.freemarker.* // ... fun Application.module() { install(FreeMarker) // ... }

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:

import freemarker.cache.* import io.ktor.server.application.* import io.ktor.server.freemarker.* fun Application.module() { install(FreeMarker) { templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates") } }

Send a template in response

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

<html> <body> <h1>Hello, ${user.name}!</h1> </body> </html>

A data model for a user looks as follows:

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:

get("/index") { val sampleUser = User(1, "John") call.respond(FreeMarkerContent("index.ftl", mapOf("user" to sampleUser))) }
Last modified: 21 September 2022