Ktor 3.0.1 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-server-html-builder artifact for HTML DSL:

    implementation("io.ktor:ktor-server-html-builder:$ktor_version")
    implementation "io.ktor:ktor-server-html-builder:$ktor_version"
    <dependency> <groupId>io.ktor</groupId> <artifactId>ktor-server-html-builder-jvm</artifactId> <version>${ktor_version}</version> </dependency>
  2. The kotlin-css-jvm artifact for building CSS:

    implementation("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>

    You can replace $kotlin_css_version with the required version of the kotlin-css artifact, for example, 1.0.0-pre.625.

Serve CSS

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 = 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: css-dsl.

Last modified: 02 April 2024