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:
Gradle (Groovy)
Gradle (Kotlin)
Maven
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 …
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
:
import io.ktor.velocity.*
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
import org.apache.velocity.runtime.RuntimeConstants
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)))
}