Skip to content
Server Plugin

머스테치

필수 의존성: io.ktor:ktor-server-mustache

코드 예시: mustache

네이티브 서버
Ktor는 Kotlin/Native를 지원하며 추가 런타임 또는 가상 머신 없이 서버를 실행할 수 있습니다.
지원: ✖️

Ktor는 Mustache 템플릿을 애플리케이션 내 뷰로 사용할 수 있도록 Mustache 플러그인을 설치할 수 있습니다.

의존성 추가

Mustache을 사용하려면 빌드 스크립트에 ktor-server-mustache 아티팩트를 포함해야 합니다:

Kotlin
Groovy
XML

Mustache 설치

Mustache 플러그인을 애플리케이션에 설치하려면, 지정된

모듈
모듈을 사용하면 라우트를 그룹화하여 애플리케이션을 구조화할 수 있습니다.
에서 install 함수에 전달합니다. 아래 코드 스니펫은 Mustache을 설치하는 방법을 보여줍니다...

  • ... embeddedServer 함수 호출 내.
  • ... Application 클래스의 확장 함수인 명시적으로 정의된 module 내.
kotlin
kotlin

install 블록 내에서 Mustache 템플릿 로드를 위한 MustacheFactory구성할 수 있습니다.

Mustache 구성

템플릿 로딩 구성

템플릿을 로드하려면 MustacheFactorymustacheFactory 프로퍼티에 할당해야 합니다. 예를 들어, 아래 코드 스니펫은 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)

지정된 경로에 템플릿을 사용하려면 다음과 같이 call.respond 메서드에 MustacheContent를 전달합니다:

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