Server Plugin
Velocity
Ktor 允許您透過安裝 Velocity 外掛程式,在應用程式中將 Velocity 範本 作為視圖使用。
新增依賴項
若要使用 Velocity
,您需要在建置腳本中包含 ktor-server-velocity
artifact:
Kotlin
Groovy
XML
安裝 Velocity
若要將 Velocity
外掛程式安裝到應用程式中,請在指定的
模組
中將其傳遞給 模組允許您透過將路由分組來建構應用程式。
install
函數。以下程式碼片段展示了如何安裝 Velocity
... - ... 在
embeddedServer
函數呼叫內部。 - ... 在明確定義的
module
內部,該模組是Application
類別的一個擴展函數。
kotlin
kotlin
您可以選擇安裝 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 {
// Engine configuration
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() // Add a default tool
tool("foo", MyCustomTool::class.java) // Add a custom tool
}