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:

Velocity - 图1

Gradle (Groovy)

Gradle (Kotlin)

Maven

Velocity - 图2

  1. implementation "io.ktor:ktor-velocity:$ktor_version"

Install Velocity

To install the Velocity feature, pass it to the install function in the application initialization code. This can be the main function …

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.main() {
  4. install(Velocity)
  5. // ...
  6. }

… or a specified module:

  1. import io.ktor.features.*
  2. // ...
  3. fun Application.module() {
  4. install(Velocity)
  5. // ...
  6. }

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:

  1. import io.ktor.velocity.*
  2. import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
  3. import org.apache.velocity.runtime.RuntimeConstants
  4. install(Velocity) {
  5. setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath")
  6. setProperty("classpath.resource.loader.class", ClasspathResourceLoader::class.java.name)
  7. }

Send a Template in Response

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

  1. <html>
  2. <body>
  3. <h1>Hello, $user.name</h1>
  4. </body>
  5. </html>

A data model for a user looks as follows:

  1. 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:

  1. get("/index") {
  2. val sampleUser = User(1, "John")
  3. call.respond(VelocityContent("templates/index.vl", mapOf("user" to sampleUser)))
  4. }