Ktor 2.1.1 Help

Velocity

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

Add dependencies

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

implementation("io.ktor:ktor-server-velocity:$ktor_version")
implementation "io.ktor:ktor-server-velocity:$ktor_version"
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-velocity-jvm</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.server.application.* import io.ktor.server.velocity.* // ... fun main() { embeddedServer(Netty, port = 8080) { install(Velocity) // ... }.start(wait = true) }

... or a specified module.

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

Optionally, you can install the VelocityTools plugin to have the capability to add standard and custom Velocity tools.

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:

import io.ktor.server.application.* import io.ktor.server.velocity.* import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader import org.apache.velocity.runtime.RuntimeConstants fun Application.module() { 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))) }

Add Velocity tools

If you've installed the VelocityTools plugin, you can access the EasyFactoryConfiguration instance inside the install block to add standard and custom Velocity tools, for example:

install(VelocityTools) { engine { // Engine configuration setProperty("resource.loader", "string") addProperty("resource.loader.string.name", "myRepo") addProperty("resource.loader.string.class", StringResourceLoader::class.java.name) addProperty("resource.loader.string.repository.name", "myRepo") } addDefaultTools() // Add a default tool tool("foo", MyCustomTool::class.java) // Add a custom tool }
Last modified: 21 September 2022