Server Plugin
FreeMarker
必須の依存関係: io.ktor:ktor-server-freemarker
コード例: freemarker
ネイティブサーバーサポート: ✖️ Ktor supports Kotlin/Native and allows you to run a server without an additional runtime or virtual machine.
Ktorは、FreeMarkerプラグインをインストールすることで、アプリケーション内でFreeMarkerテンプレートをビューとして使用できます。
依存関係を追加
FreeMarker
を使用するには、ビルドスクリプトにktor-server-freemarker
アーティファクトを含める必要があります:
Kotlin
Groovy
XML
FreeMarkerをインストール
アプリケーションにFreeMarker
プラグインをインストールするには、 指定された
モジュール
内のModules allow you to structure your application by grouping routes.
install
関数に渡します。 以下のコードスニペットは、FreeMarker
をインストールする方法を示しています... - ...
embeddedServer
関数呼び出し内で。 - ...
Application
クラスの拡張関数である、明示的に定義されたmodule
内で。
kotlin
kotlin
install
ブロック内では、FreeMarkerテンプレートをロードするために、目的のTemplateLoaderを設定できます。
FreeMarkerを設定
テンプレートのロードを設定
テンプレートをロードするには、目的のTemplateLoaderタイプをtemplateLoader
プロパティに割り当てる必要があります。例えば、以下のコードスニペットは、Ktorが現在のクラスパスに対するtemplates
パッケージ内でテンプレートを探せるようにします:
kotlin
import freemarker.cache.*
import io.ktor.server.application.*
import io.ktor.server.freemarker.*
fun Application.module() {
install(FreeMarker) {
templateLoader = ClassTemplateLoader(this::class.java.classLoader, "templates")
}
}
レスポンスでテンプレートを送信
resources/templates
にindex.ftl
テンプレートがあるとします:
html
<html>
<body>
<h1>Hello, ${user.name}!</h1>
</body>
</html>
ユーザーのデータモデルは以下のようになります:
kotlin
data class User(val id: Int, val name: String)
指定されたルートにテンプレートを使用するには、以下のようにFreeMarkerContent
をcall.respond
メソッドに渡します:
kotlin
get("/index") {
val sampleUser = User(1, "John")
call.respond(FreeMarkerContent("index.ftl", mapOf("user" to sampleUser)))
}