Skip to content
Server Plugin

Mustache

必要な依存関係: io.ktor:ktor-server-mustache

コード例: mustache

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

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

依存関係の追加 ​

Mustache を使用するには、ビルドスクリプトに ktor-server-mustache アーティファクトを追加します。

kotlin
implementation(ktorLibs.server.mustache)
上記のコードスニペットでは、Ktor の依存関係を指定するために Ktor バージョンカタログ を使用しています。
groovy
implementation ktorLibs.server.mustache
上記のコードスニペットでは、Ktor の依存関係を指定するために Ktor バージョンカタログ を使用しています。
xml
<dependency>
    <groupId>io.ktor</groupId>
    <artifactId>ktor-server-mustache-jvm</artifactId>
    <version>${ktor_version}</version>
</dependency>

Mustache のインストール ​

Mustache プラグインをアプリケーションにインストールするには、指定されたモジュールモジュールを使用すると、ルートをグループ化してアプリケーションを構造化できます。内の install 関数に渡します。 次の例は、Mustache をインストールする方法を示しています。

  • embeddedServer() 関数の呼び出し内。
  • Application クラスで明示的に定義された module() 拡張関数内。
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.mustache.*

fun main() {
    embeddedServer(Netty, port = 8080) {
        install(Mustache)
        // ...
    }.start(wait = true)
}
kotlin
import io.ktor.server.application.*
import io.ktor.server.mustache.*
// ...
fun Application.module() {
    install(Mustache)
    // ...
}

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/templates に index.hbs テンプレートがある場合を想定します。

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

ユーザーのデータモデルは次のようになります。

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

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

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