Server Plugin
Thymeleaf
필수 의존성: io.ktor:ktor-server-thymeleaf
코드 예시: thymeleaf
네이티브 서버 지원: ✖️ Ktor supports Kotlin/Native and allows you to run a server without an additional runtime or virtual machine.
Ktor를 사용하면 Thymeleaf 플러그인을 설치하여 애플리케이션 내에서 Thymeleaf 템플릿을 뷰로 사용할 수 있습니다.
의존성 추가
Thymeleaf
을(를) 사용하려면 빌드 스크립트에 ktor-server-thymeleaf
아티팩트를 포함해야 합니다:
Kotlin
Groovy
XML
Thymeleaf 설치
애플리케이션에 Thymeleaf
플러그인을 설치하려면, 지정된
모듈
에서 Modules allow you to structure your application by grouping routes.
install
함수에 전달합니다. 아래 코드 스니펫은 Thymeleaf
을(를) 설치하는 방법을 보여줍니다... - ...
embeddedServer
함수 호출 내에서. - ...
Application
클래스의 확장 함수인 명시적으로 정의된module
내에서.
kotlin
kotlin
Thymeleaf 구성
템플릿 로딩 구성
install
블록 내에서 ClassLoaderTemplateResolver
를 구성할 수 있습니다. 예를 들어, 아래 코드 스니펫은 Ktor가 현재 클래스 경로를 기준으로 templates
패키지에서 *.html
템플릿을 찾도록 활성화합니다:
kotlin
import io.ktor.server.application.*
import io.ktor.server.thymeleaf.*
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver
fun Application.module() {
install(Thymeleaf) {
setTemplateResolver(ClassLoaderTemplateResolver().apply {
prefix = "templates/"
suffix = ".html"
characterEncoding = "utf-8"
})
}
}
응답으로 템플릿 전송
resources/templates
에 index.html
템플릿이 있다고 가정해 봅시다:
html
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1 th:text="'Hello, ' + ${user.name}"></h1>
</body>
</html>
사용자 데이터 모델은 다음과 같습니다:
kotlin
data class User(val id: Int, val name: String)
지정된 경로에 템플릿을 사용하려면, 다음과 같이 ThymeleafContent를 call.respond
메서드에 전달합니다:
kotlin
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}
예시: Thymeleaf 템플릿 자동 재로드
아래 예시는 개발 모드를 사용할 때 Thymeleaf 템플릿을 자동으로 재로드하는 방법을 보여줍니다.
kotlin
package com.example
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.thymeleaf.*
import org.thymeleaf.templateresolver.*
fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)
fun Application.module() {
install(Thymeleaf) {
setTemplateResolver((if (developmentMode) {
FileTemplateResolver().apply {
cacheManager = null
prefix = "src/main/resources/templates/"
}
} else {
ClassLoaderTemplateResolver().apply {
prefix = "templates/"
}
}).apply {
suffix = ".html"
characterEncoding = "utf-8"
})
}
routing {
get("/index") {
val sampleUser = User(1, "John")
call.respond(ThymeleafContent("index", mapOf("user" to sampleUser)))
}
}
}
data class User(val id: Int, val name: String)
전체 예시는 여기서 확인할 수 있습니다: thymeleaf-auto-reload.