Ktor 1.6.4 Help


Ktor allows you to use Velocity templates as views within your application by installing the Velocity plugin (previously known as feature).

Add dependencies

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

implementation "io.ktor:ktor-velocity:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-velocity</artifactId> <version>${ktor_version}</version> </dependency>

Install Velocity

To install the Velocity 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.features.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(Velocity) // ... }.start(wait = true) }

... or a specified module.

import io.ktor.features.* // ... fun Application.module() { install(Velocity) // ... }

Configure Velocity

Configure template loading

Inside the install block, you can configure the VelocityEngine. For example, if you want to use templates from the classpath, use a resource loader for classpath:

install(Velocity) { setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath") setProperty("classpath.resource.loader.class", ClasspathResourceLoader::class.java.name) }

Send a template in response

Imagine you have the index.vl 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 VelocityContent to the call.respond method in the following way:

get("/index") { val sampleUser = User(1, "John") call.respond(VelocityContent("templates/index.vl", mapOf("user" to sampleUser))) }
Last modified: 28 May 2021