Skip to content
Server Plugin

Velocity

必要相依性: io.ktor:ktor-server-velocity

程式碼範例: velocity

原生伺服器Ktor 支援 Kotlin/Native,可讓您在無需額外執行階段或虛擬機的情況下執行伺服器。 支援: ✖️

透過安裝 Velocity 外掛程式,Ktor 允許你在應用程式中使用 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) // 新增自訂工具
}