改进翻译

Typesafe HTML DSL

最近更新 2020-02-23
How to construct DOM elements using kotlinx.html and Kotlin DSLs.

The kotlinx.html library provides the ability to generate DOM elements using statically typed HTML builders (and besides JavaScript, it is even available on the JVM target!) To use the library, we need to include the corresponding repository and dependency to our build.gradle.kts file:

repositories {
    // ...
    jcenter()
}

dependencies {
    implementation(kotlin("stdlib-js"))
    implementation("org.jetbrains.kotlinx:kotlinx-html-js:0.7.1")
    // ...
}

Once the dependency is included, we can access the different interfaces provided to generate our DOM. To render a headline, some text, and a link, the following snippet would be sufficient, for example:

import kotlinx.browser.*
import kotlinx.html.*
import kotlinx.html.dom.*

fun main() {
    document.body!!.append.div {
        h1 {
            +"Welcome to Kotlin/JS!"
        }
        p {
            +"Fancy joining this year's "
            a("https://kotlinconf.com/") {
                +"KotlinConf"
            }
            +"?"
        }
    }
}

When running this example in the browser, the DOM will be assembled in a straightforward way. This is easily confirmed by checking the Elements of the website using the developer tools of our browser:

Rendering a website from kotlinx.html

To learn more about the kotlinx.html library, check out the GitHub Wiki, where you can find more information about how to create elements without adding them to the DOM, binding to events like onClick, and examples on how to apply CSS classes to your HTML elements, to name just a few.