Skip to content
Server Plugin

Velocity

必需依赖项:io.ktor:ktor-server-velocity

代码示例: velocity

原生服务器Ktor 支持 Kotlin/Native,并允许您在无需额外运行时或虚拟机的情况下运行服务器。支持:✖️

Ktor 允许你通过安装 Velocity 插件,在应用程序中将 Velocity 模板用作视图。

添加依赖项 ​

要使用 Velocity,请将 ktor-server-velocity 工件添加到构建脚本中:

kotlin
implementation(ktorLibs.server.velocity)
上述代码段使用 Ktor 版本目录 来指定 Ktor 依赖项。
groovy
implementation ktorLibs.server.velocity
上述代码段使用 Ktor 版本目录 来指定 Ktor 依赖项。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-velocity-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

安装 Velocity ​

要将 Velocity 插件安装到应用程序中, 请将其传递给指定模块模块允许您通过对路由进行分组来构建应用程序结构。中的 install 函数。 以下示例展示了如何安装 Velocity:

  • 在 embeddedServer() 函数调用中。
  • 在 Application 类上显式定义的 module() 扩展函数中。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.velocity.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(Velocity)
        // ...
    }.start(wait = true)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.velocity.*
// ...
fun Application.module() {
    install(Velocity)
    // ...
}

作为可选项,你还可以安装 VelocityTools 插件,以便能够添加标准和自定义 Velocity 工具。

配置 Velocity ​

配置模板加载 ​

在 install 块内,你可以配置 VelocityEngine。例如,如果你想使用 classpath 中的模板,请使用适用于 classpath 的资源加载器:

kotlin
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)
    }
}

在响应中发送模板 ​

假设你在 resources/templates 中有一个 index.vl 模板:

html
<html>
    <body>
        <h1>Hello, $user.name</h1>
    </body>
</html>

用户的数据模型如下所示:

kotlin
data class User(val id: Int, val name: String)

要为指定的路由使用该模板,请按以下方式将 VelocityContent 传递给 call.respond 方法:

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

添加 Velocity 工具 ​

如果你已安装了 VelocityTools 插件,可以在 install 块内访问 EasyFactoryConfiguration 实例以添加标准和自定义 Velocity 工具,例如:

kotlin
install(VelocityTools) {
    engine {
        // 引擎配置
        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() // 添加默认工具
    tool("foo", MyCustomTool::class.java) // 添加自定义工具
}