Using Velocity Templates

Ktor includes support for Velocity templates through the Velocityfeature. Initialize the Velocity feature with theVelocityEngine:

This feature is defined in the class io.ktor.velocity.Velocity in the artifact io.ktor:ktor-velocity:$ktor_version.

dependencies { implementation "io.ktor:ktor-velocity:$ktor_version"}

dependencies { implementation("io.ktor:ktor-velocity:$ktor_version")}

<project> … <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-velocity</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies></project>

Installation

You can install Velocity, and configure the VelocityEngine.

  1. install(Velocity) { // this: VelocityEngine
  2. setProperty("resource.loader", "string");
  3. addProperty("string.resource.loader.class", StringResourceLoader::class.java.name)
  4. addProperty("string.resource.loader.repository.static", "false")
  5. init() // need to call `init` before trying to retrieve string repository
  6. (getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT) as StringResourceRepository).apply {
  7. putStringResource("test.vl", "<p>Hello, \$id</p><h1>\$title</h1>")
  8. }
  9. }

Usage

When Velocity is configured, you can call the call.respond method with a VelocityContent instance:

  1. routing {
  2. val model = mapOf("id" to 1, "title" to "Hello, World!")
  3. get("/") {
  4. call.respond(VelocityContent("test.vl", model, "e"))
  5. }
  6. }