Server Plugin
FreeMarker
必須の依存関係: io.ktor:ktor-server-freemarker
コード例: freemarker
Native サーバーのサポート: ✖️ 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)指定されたルートでテンプレートを使用するには、次のように call.respond メソッドに FreeMarkerContent を渡します。
kotlin
get("/index") {
val sampleUser = User(1, "John")
call.respond(FreeMarkerContent("index.ftl", mapOf("user" to sampleUser)))
}