Skip to content
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/templatesindex.ftlテンプレートがあるとします:

html
<html>
    <body>
        <h1>Hello, ${user.name}!</h1>
    </body>
</html>

ユーザーのデータモデルは以下のようになります:

kotlin
data class User(val id: Int, val name: String)

指定されたルートにテンプレートを使用するには、以下のようにFreeMarkerContentcall.respondメソッドに渡します:

kotlin
get("/index") {
    val sampleUser = User(1, "John")
    call.respond(FreeMarkerContent("index.ftl", mapOf("user" to sampleUser)))
}