CSS DSL
必要相依性:io.ktor:ktor-server-html-builder、org.jetbrains.kotlin-wrappers:kotlin-css
程式碼範例: css-dsl
CSS DSL 擴充了 HTML DSL,並允許你透過使用 kotlin-css 包裝函式在 Kotlin 中編寫樣式表。
請參閱提供靜態內容,了解如何將樣式表作為靜態內容提供。
新增相依性
CSS DSL 不需要安裝,但需要在組建指令碼中包含以下構件:
用於 HTML DSL 的
ktor-server-html-builder構件:kotlinimplementation(ktorLibs.server.htmlBuilder)上述程式碼片段使用 Ktor 版本目錄 (version catalog) 來指定 Ktor 相依性。groovyimplementation ktorLibs.server.htmlBuilder上述程式碼片段使用 Ktor 版本目錄 (version catalog) 來指定 Ktor 相依性。xml<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-html-builder-jvm</artifactId> <version>${ktor_version}</version> </dependency>用於建置 CSS 的
kotlin-css-jvm構件:kotlinimplementation("org.jetbrains.kotlin-wrappers:kotlin-css:$kotlin_css_version")groovyimplementation "org.jetbrains.kotlin-wrappers:kotlin-css:$kotlin_css_version"xml<dependency> <groupId>org.jetbrains.kotlin-wrappers</groupId> <artifactId>kotlin-css</artifactId> <version>${kotlin_css_version}</version> </dependency>你可以將
$kotlin_css_version替換為所需的kotlin-css構件版本,例如2026.10.5。
提供 CSS
若要傳送 CSS 回應,你需要擴充 ApplicationCall,新增 respondCss 方法以將樣式表序列化為字串,並使用 CSS 內容類型傳送給用戶端:
kotlin
suspend inline fun ApplicationCall.respondCss(builder: CssBuilder.() -> Unit) {
this.respondText(CssBuilder().apply(builder).toString(), ContentType.Text.CSS)
}接著,你可以在所需的路由內提供 CSS:
kotlin
get("/styles.css") {
call.respondCss {
body {
backgroundColor = Color.darkBlue
margin = Margin(0.px)
}
rule("h1.page-title") {
color = Color.white
}
}
}最後,你可以將指定的 CSS 套用於使用 HTML DSL 建立的 HTML 文件:
kotlin
get("/html-dsl") {
call.respondHtml {
head {
link(rel = "stylesheet", href = "/styles.css", type = "text/css")
}
body {
h1(classes = "page-title") {
+"Hello from Ktor!"
}
}
}
}你可以在這裡找到完整的範例:css-dsl。
