CSS DSL
CSS DSL extends HTML DSL and allows you to author stylesheets in Kotlin by using the kotlin-css wrapper.
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:implementation "io.ktor:ktor-html-builder:$ktor_version"implementation("io.ktor:ktor-html-builder:$ktor_version")<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-html-builder</artifactId> <version>${ktor_version}</version> </dependency>The
kotlin-css-jvm
artifact for building CSS:You can replaceimplementation "org.jetbrains.kotlin-wrappers:kotlin-css:$kotlin_css_version"implementation("org.jetbrains.kotlin-wrappers:kotlin-css:$kotlin_css_version")<dependency> <groupId>org.jetbrains.kotlin-wrappers</groupId> <artifactId>kotlin-css</artifactId> <version>${kotlin_css_version}</version> </dependency>$kotlin_css_version
with the required version of thekotlin-css
artifact, for example,1.0.0-pre.256-kotlin-1.5.31
.
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!"
}
}
}
}
You can find the full example here: caching-headers.
Last modified: 11 May 2022