Using Velocity Templates

预计阅读时间:1分钟

Ktor通过Velocity功能包括对Velocity模板的支持. 初始化用的测速功能VelocityEngine

此功能定义在类io.ktor.velocity.Velocity在神器io.ktor:ktor-velocity:$ktor_version .
dependencies { implementation "io.ktor:ktor-velocity:$ktor_version" }
dependencies { implementation("io.ktor:ktor-velocity:$ktor_version") }
<project> ... <dependencies> <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-velocity</artifactId> <version>${ktor.version}</version> <scope>compile</scope> </dependency> </dependencies> </project>

Installation

您可以安装Velocity,并配置VelocityEngine .

install(Velocity) { // this: VelocityEngine
    setProperty("resource.loader", "string");
    addProperty("string.resource.loader.class", StringResourceLoader::class.java.name)
    addProperty("string.resource.loader.repository.static", "false")
    init() // need to call `init` before trying to retrieve string repository
    
    (getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT) as StringResourceRepository).apply {
        putStringResource("test.vl", "<p>Hello, \$id</p><h1>\$title</h1>")
    }
}

Usage

配置了Velocity后,可以使用VelocityContent实例调用call.respond方法:

routing {
    val model = mapOf("id" to 1, "title" to "Hello, World!")

    get("/") {
        call.respond(VelocityContent("test.vl", model, "e"))
    }
}

by  ICOPY.SITE