Ktor 1.5.4 Help

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:

  1. 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>

  2. The kotlin-css-jvm artifact for building CSS:

    implementation "org.jetbrains:kotlin-css-jvm:$kotlin_css_version"
    implementation("org.jetbrains:kotlin-css-jvm:$kotlin_css_version")
    <dependency> <groupId>org.jetbrains</groupId> <artifactId>kotlin-css-jvm</artifactId> <version>${kotlin_css_version}</version> </dependency>

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!" } } } }
Last modified: 19 April 2021