Ktor 1.5.4 Help

Velocity

Ktor allows you to use Velocity templates as views within your application by installing the Velocity 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"
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 feature, pass it to the install function in the application initialization code. This can be the main function ...

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

... 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: 19 April 2021