Skip to content
Server Plugin

Mustache

必須の依存関係: io.ktor:ktor-server-mustache

コード例: mustache

Nativeサーバー
KtorはKotlin/Nativeをサポートしており、追加のランタイムや仮想マシンなしでサーバーを実行できます。
のサポート: ✖️

Ktorでは、Mustacheプラグインをインストールすることで、アプリケーション内でMustacheテンプレートをビューとして使用できます。

依存関係の追加

Mustacheを使用するには、ビルドスクリプトにktor-server-mustacheアーティファクトを含める必要があります。

Kotlin
Groovy
XML

Mustacheのインストール

Mustacheプラグインをアプリケーションにインストールするには、指定された

モジュール
モジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。
内のinstall関数に渡します。 以下のコードスニペットは、Mustacheをインストールする方法を示しています。

  • ... embeddedServer関数の呼び出し内。
  • ... 明示的に定義されたmoduleApplicationクラスの拡張関数)内。
kotlin
kotlin

installブロック内では、Mustacheテンプレートを読み込むためのMustacheFactory設定できます。

Mustacheの設定

テンプレートの読み込み設定

テンプレートを読み込むには、mustacheFactoryプロパティにMustacheFactoryを割り当てる必要があります。例えば、以下のコードスニペットでは、Ktorが現在のクラスパスを基準としたtemplatesパッケージからテンプレートを検索できるように設定しています。

kotlin
import com.github.mustachejava.DefaultMustacheFactory
import io.ktor.server.application.*
import io.ktor.server.mustache.Mustache
import io.ktor.server.mustache.MustacheContent

fun Application.module() {
    install(Mustache) {
        mustacheFactory = DefaultMustacheFactory("templates")
    }
}

レスポンスでテンプレートを送信する

resources/templatesindex.hbsテンプレートがあると仮定します。

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

ユーザーのデータモデルは以下の通りです。

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

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

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