CSS DSL
CSS DSL extends HTML DSL and allows you to author stylesheets in Kotlin by using the kotlin-css wrapper.
tip
Learn how to serve stylesheets as static content from Serving Static Content.
Add Dependencies
CSS DSL doesn’t need installation, but requires including the following artifacts in the build script:
The
ktor-html-builder
artifact for HTML DSL:Gradle (Groovy)
Gradle (Kotlin)
Maven
implementation "io.ktor:ktor-html-builder:$ktor_version"
The
kotlin-css-jvm
artifact for building CSS:Gradle (Groovy)
Gradle (Kotlin)
Maven
implementation "org.jetbrains:kotlin-css-jvm:$1.0.0-pre.129-kotlin-1.4.20"
Use CSS DSL
To send a CSS response, you need to extend ApplicationCall
by adding the respondCss
method to serialize a stylesheet into a string and send it to the client with the CSS
content type:
suspend inline fun ApplicationCall.respondCss(builder: CSSBuilder.() -> Unit) {
this.respondText(CSSBuilder().apply(builder).toString(), ContentType.Text.CSS)
}
Then, you can provide CSS inside the required route:
get("/styles.css") {
call.respondCss {
body {
backgroundColor = Color.darkBlue
margin(0.px)
}
rule("h1.page-title") {
color = Color.white
}
}
}
Finally, you can use the specified CSS for an HTML document created with HTML DSL:
get("/html-dsl") {
call.respondHtml {
head {
link(rel = "stylesheet", href = "/styles.css", type = "text/css")
}
body {
h1(classes = "page-title") {
+"Hello from Ktor!"
}
}
}
}