Velocity
必要な依存関係: io.ktor:ktor-server-velocity
コード例: velocity
Native サーバーKtorはKotlin/Nativeをサポートしており、追加のランタイムや仮想マシンなしでサーバーを実行できます。のサポート: ✖️
Ktor では、Velocity プラグインをインストールすることで、Velocity テンプレートをアプリケーション内のビューとして使用できます。
依存関係の追加
Velocity を使用するには、ビルドスクリプトに ktor-server-velocity アーティファクトを追加します。
implementation(ktorLibs.server.velocity)implementation ktorLibs.server.velocity<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-velocity-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>Velocity のインストール
Velocity プラグインをアプリケーションにインストールするには、指定されたモジュールモジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。内の install 関数に渡します。 以下の例は、Velocity をインストールする方法を示しています。
embeddedServer()関数の呼び出し内。Applicationクラスに明示的に定義されたmodule()拡張関数内。
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)
}import io.ktor.server.application.*
import io.ktor.server.velocity.*
// ...
fun Application.module() {
install(Velocity)
// ...
}必要に応じて、VelocityTools プラグインをインストールすることで、標準およびカスタムの Velocity ツールを追加する機能を利用できます。
Velocity の設定
テンプレート読み込みの設定
install ブロック内で、VelocityEngine を設定できます。例えば、クラスパスからテンプレートを使用したい場合は、classpath 用のリソースローダーを使用します。
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>
<body>
<h1>Hello, $user.name</h1>
</body>
</html>ユーザーのデータモデルは以下のようになります。
data class User(val id: Int, val name: String)指定されたルートでテンプレートを使用するには、次のように VelocityContent を call.respond メソッドに渡します。
get("/index") {
val sampleUser = User(1, "John")
call.respond(VelocityContent("templates/index.vl", mapOf("user" to sampleUser)))
}Velocity ツールの追加
VelocityTools プラグインをインストールしている場合は、install ブロック内で EasyFactoryConfiguration インスタンスにアクセスして、標準およびカスタムの Velocity ツールを追加できます。例えば、次のようになります。
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) // カスタムツールを追加
}