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 响应,你需要通过添加 respondCss 方法来扩展 ApplicationCall,以将样式表序列化为字符串,并使用 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。
