Server Plugin
Pebble
필수 의존성: io.ktor:ktor-server-pebble
코드 예제: pebble
네이티브 서버Ktor는 Kotlin/Native를 지원하므로 추가 런타임이나 가상 머신 없이도 서버를 실행할 수 있습니다. 지원: ✖️
Ktor에서는 Pebble 플러그인을 설치하여 애플리케이션 내에서 Pebble 템플릿을 뷰로 사용할 수 있습니다.
의존성 추가
Pebble을(를) 사용하려면 빌드 스크립트에 ktor-server-pebble 아티팩트를 추가하세요:
kotlin
implementation(ktorLibs.server.pebble) 위 코드 스니펫은 Ktor 의존성을 지정하기 위해 Ktor 버전 카탈로그를 사용합니다.
groovy
implementation ktorLibs.server.pebble 위 코드 스니펫은 Ktor 의존성을 지정하기 위해 Ktor 버전 카탈로그를 사용합니다.
xml
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-pebble-jvm</artifactId>
<version>${ktor_version}</version>
</dependency>Pebble 설치
애플리케이션에 Pebble 플러그인을 설치하려면 지정된 모듈모듈을 사용하면 라우트를 그룹화하여 애플리케이션의 구조를 설계할 수 있습니다.의 install 함수에 전달하세요. 다음 예제는 Pebble을(를) 설치하는 방법을 보여줍니다:
embeddedServer()함수 호출 내에서Application클래스에 명시적으로 정의된module()확장 함수 내에서
kotlin
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.pebble.*
fun main() {
embeddedServer(Netty, port = 8080) {
install(Pebble)
// ...
}.start(wait = true)
}kotlin
import io.ktor.server.application.*
import io.ktor.server.pebble.*
// ...
fun Application.module() {
install(Pebble)
// ...
}install 블록 내에서 Pebble 템플릿을 로드하기 위한 PebbleEngine.Builder를 구성할 수 있습니다.
Pebble 구성
템플릿 로딩 구성
템플릿을 로드하려면 PebbleEngine.Builder를 사용하여 템플릿 로드 방식을 구성해야 합니다. 예를 들어, 아래 코드 스니펫은 Ktor가 현재 클래스패스를 기준으로 templates 패키지에서 템플릿을 찾을 수 있도록 설정합니다:
kotlin
import io.ktor.server.application.*
import io.ktor.server.pebble.*
import io.ktor.server.response.*
fun Application.module() {
install(Pebble) {
loader(ClasspathLoader().apply {
prefix = "templates"
})
}
}응답으로 템플릿 전송
resources/templates에 다음과 같은 index.html 템플릿이 있다고 가정해 보겠습니다:
html
<html>
<body>
<h1>Hello, {{user.name}}</h1>
</body>
</html>사용자 데이터 모델은 다음과 같습니다:
kotlin
data class User(val id: Int, val name: String)지정된 라우트에 템플릿을 사용하려면 다음과 같이 call.respond 메서드에 PebbleContent를 전달합니다:
kotlin
get("/index") {
val sampleUser = User(1, "John")
call.respond(PebbleContent("index.html", mapOf("user" to sampleUser)))
}