### Install kotlinx.html via NPM Source: https://github.com/kotlin/kotlinx.html/wiki/Getting-started Install the kotlinx-html package for use in JavaScript projects via NPM. ```bash npm install kotlinx-html ``` -------------------------------- ### Generate HTML to Stdout Source: https://github.com/kotlin/kotlinx.html/wiki/Streaming Example demonstrating how to generate HTML content and append it to standard output using appendHTML. ```kotlin System.out.appendHTML().div { h1 { + "Heading 1" } } ``` -------------------------------- ### Build DOM Tree with Kotlinx.html (JavaScript) Source: https://github.com/kotlin/kotlinx.html/blob/master/README-JS.md Example of building a DOM tree using kotlinx.html for JavaScript-targeted Kotlin. It demonstrates creating divs and paragraphs with links, and appending them to an existing element. ```kotlin window.setInterval({ val myDiv = document.create.div("panel") { p { +"Here is " a("https://kotlinlang.org") { + "official Kotlin site" } } } document.getElementById("container")!!.appendChild(myDiv) document.getElementById("container")!!.append { div { +"added it" } } }, 1000L) ``` -------------------------------- ### Stream HTML to Writer/Appendable with Kotlinx.html (JVM) Source: https://github.com/kotlin/kotlinx.html/blob/master/README-JS.md Example of building HTML directly to a Writer or Appendable using kotlinx.html on the JVM. It shows how to create a simple HTML structure with a body and a link. ```kotlin System.out.appendHTML().html { body { div { a("https://kotlinlang.org") { target = ATarget.blank +"Main site" } } } } ``` -------------------------------- ### Using Custom Tag on Root Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing Example of using the custom `custom` tag directly at the root level, showcasing its availability outside of specific parent elements. ```kotlin buildString { appendHTML(false).custom { span { +"content" } } } ``` -------------------------------- ### Form Elements and Input Shortcuts in Kotlin HTML DSL Source: https://context7.com/kotlin/kotlinx.html/llms.txt Illustrates using convenient shortcut functions for various input types within forms, reducing boilerplate code. Includes examples for text, email, password, checkboxes, radio buttons, file uploads, selects, textareas, and submit buttons. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML val html = createHTML().form { action = "/register" method = FormMethod.post encType = FormEncType.multipartFormData // Using input shortcuts (cleaner syntax) label { +("Username: ") textInput(name = "username") { placeholder = "Enter username" required = true } } br() label { +("Email: ") emailInput(name = "email") { required = true } } br() label { +("Password: ") passwordInput(name = "password") { minLength = "8" } } br() // Checkbox inputs label { checkBoxInput(name = "remember") { checked = true } +(" Remember me") } br() // Radio buttons radioInput(name = "plan") { value = "free" } label { + ``` ```kotlin "Free" } radioInput(name = "plan") { value = "pro" } label { + ``` ```kotlin "Pro" } br() // File upload fileInput(name = "avatar") { accept = "image/*" } br() // Select dropdown select { name = "country" option { value = ""; + ``` ```kotlin "Select country" } option { value = "us"; + ``` ```kotlin "United States" } option { value = "uk"; + ``` ```kotlin "United Kingdom" } option { value = "de"; selected = true; + ``` ```kotlin "Germany" } } br() // Textarea textArea { name = "bio" rows = "4" cols = "50" placeholder = "Tell us about yourself" } br() // Submit button submitInput { value = "Register" } } ``` -------------------------------- ### Using Custom Tag Inside DIV Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing Example of using the custom `custom` tag within a `div` element, demonstrating its integration into existing structures. ```kotlin buildString { appendHTML(false).div { custom { span { + content" } } } } ``` -------------------------------- ### Implement Custom Logging Interceptor for HTML Generation Source: https://context7.com/kotlin/kotlinx.html/llms.txt Create a custom interceptor to log tag start and end events during HTML generation. This aids in debugging and understanding the HTML building process. ```kotlin import kotlinx.html.* import kotlinx.html.stream.* import kotlinx.html.consumers.* // Custom interceptor for logging fun TagConsumer.logged(): TagConsumer = object : TagConsumer by this { override fun onTagStart(tag: Tag) { println("Starting tag: ${tag.tagName}") this@logged.onTagStart(tag) } override fun onTagEnd(tag: Tag) { println("Ending tag: ${tag.tagName}") this@logged.onTagEnd(tag) } } // Usage with custom interceptor val debugHtml = createHTML().logged().div { p { + ``` ```kotlin "Test" } ``` -------------------------------- ### Inject HTML Elements into Class Fields Source: https://github.com/kotlin/kotlinx.html/wiki/Injector Instantiate a class and use the `inject` function to map HTML elements (identified by class or tag name) to the class's fields. This example injects a div by class name and a paragraph by tag name. ```kotlin val bean = ExampleBean() document.create.inject(bean, listOf( InjectByClassName("my-class") to ExampleBean::myDiv, InjectByTagName("p") to ExampleBean::myP )).div { div("my-class") { p { +"test" } } } ``` -------------------------------- ### Modify CSS Classes Within Content Lambda Source: https://github.com/kotlin/kotlinx.html/wiki/Elements-CSS-classes You can modify an element's classes after its creation by accessing the 'classes' property within the content lambda. Note that in streaming mode, modifications are restricted after the tag start is written. ```kotlin div { classes = setOf("container", "left", "tree") classes += "siteHeader" } ``` -------------------------------- ### Build Project with Maven Source: https://github.com/kotlin/kotlinx.html/wiki/Development Use this command to clean and package the entire project using Maven. ```bash ./mvnw clean package ``` -------------------------------- ### Simplified Dropdown Creation Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing Demonstrates the usage of the custom extension functions to create a dropdown with significantly reduced boilerplate code. ```kotlin createHTML().ul { dropdown { dropdownToggle { + Dropdown" } dropdownMenu { li { a("#") { + Action" } } li { a("#") { + Another action" } } li { a("#") { + Something else here" } } divider() dropdownHeader("Nav header") li { a("#") { + Separated link" } } li { a("#") { + One more separated link" } } } } } ``` -------------------------------- ### Build DOM Trees with document.create Source: https://context7.com/kotlin/kotlinx.html/llms.txt In browser/JavaScript environments, use document.create to build DOM elements directly. These elements can be manipulated and appended to the document. ```kotlin import kotlinx.browser.document import kotlinx.html.* import kotlinx.html.dom.* // Create a DOM element without adding to document val myDiv = document.create.div("container") { p { +"Here is " a("https://kotlinlang.org") { +"official Kotlin site" } } } // myDiv is an HTMLDivElement ready to use ``` ```kotlin // Create and immediately append to document body document.body?.append { div { p { +"This is added to the document" } } } ``` ```kotlin // Prepend elements to beginning of a container document.getElementById("container")?.prepend { div("header") { h1 { +"Page Title" } } } ``` ```kotlin // Create complex structures val card = document.create.div("card") { div("card-header") { h3 { +"Card Title" } } div("card-body") { p { +"Card content goes here" } button(classes = "btn btn-primary") { +"Click Me" } } } document.body?.appendChild(card) ``` -------------------------------- ### Create HTML Strings with createHTML Source: https://context7.com/kotlin/kotlinx.html/llms.txt Use createHTML() to generate HTML strings. Options include pretty printing and XHTML compatibility. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML // Basic HTML generation val html = createHTML().html { head { title("My Page") meta(charset = "UTF-8") } body { h1 { +"Welcome" } p { +"This is a paragraph." } } } ``` ```kotlin // Compact output without pretty printing val compact = createHTML(prettyPrint = false).div { p { +"No extra whitespace" } } ``` ```kotlin // XHTML-compatible output with self-closing tags val xhtml = createHTML(prettyPrint = false, xhtmlCompatible = true).div { br() img(src = "image.png") } ``` -------------------------------- ### Build HTML to Stream Source: https://github.com/kotlin/kotlinx.html/blob/master/README.md This snippet demonstrates building HTML directly to a Writer (JVM) or Appendable (Multiplatform) using the kotlinx.html DSL. It requires the appendHTML extension function. ```kotlin System.out.appendHTML().html { body { div { a("https://kotlinlang.org") { target = ATarget.blank +"Main site" } } } } ``` -------------------------------- ### Add kotlinx.html JVM Dependency for Maven Source: https://github.com/kotlin/kotlinx.html/wiki/Getting-started Add the kotlinx-html-jvm dependency for server-side development using Maven. ```xml org.jetbrains.kotlinx kotlinx-html-jvm ${kotlinx.html.version} ``` -------------------------------- ### Working with CSS Classes in Kotlin HTML DSL Source: https://context7.com/kotlin/kotlinx.html/llms.txt Demonstrates setting CSS classes using the `classes` parameter and modifying them dynamically via the `classes` property. Supports space-separated strings and sets for multiple classes. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML val html = createHTML(prettyPrint = false).div { // Classes via parameter (space-separated) div(classes = "container left tree") { +("Content") } // Output:
Content
// Modify classes inside lambda div { classes = setOf("card", "shadow") classes += "active" classes += "highlighted" +("Card content") } // Output:
Card content
// Conditional classes val isActive = true div(classes = "btn" + if (isActive) " btn-active" else "") { +("Button") } // Bootstrap-style components nav(classes = "navbar navbar-expand-lg navbar-dark bg-dark") { a(classes = "navbar-brand", href = "#") { +("Brand") } } } ``` -------------------------------- ### Using Type Shortcuts for Input Fields Source: https://github.com/kotlin/kotlinx.html/wiki/Enum-attributes Utilize generated type shortcuts like `textInput`, `checkBoxInput`, and `fileInput` to simplify the declaration of common input fields, making forms more readable. ```kotlin form(action = "/form", encType = FormEncType.multipartFormData, method = FormMethod.post) { textInput(name = "field1") textInput(name = "field2") checkBoxInput(name = "field3") textInput(name = "field4") fileInput(name = "field5") textInput(name = "field6") } ``` -------------------------------- ### Add kotlinx.html to Gradle JVM Project Source: https://github.com/kotlin/kotlinx.html/wiki/Getting-started Include the kotlinx-html-jvm dependency for server-side Kotlin projects using Gradle. ```groovy dependencies { //Fill this in with the version of kotlinx in use in your project def kotlinx_html_version = "your_version_here" // include for JVM target implementation("org.jetbrains.kotlinx:kotlinx-html-jvm:${kotlinx_html_version}") // include for JS target implementation("org.jetbrains.kotlinx:kotlinx-html-js:${kotlinx_html_version}") // include for Common module implementation("org.jetbrains.kotlinx:kotlinx-html:${kotlinx_html_version}") } ``` -------------------------------- ### Create HTML Text Source: https://github.com/kotlin/kotlinx.html/wiki/Streaming Use the createHTML function as a shortcut to generate only the text representation of HTML content. ```kotlin val text = createHTML().div { // content here } ``` -------------------------------- ### Add kotlinx.html to Gradle Kotlin DSL Project Source: https://github.com/kotlin/kotlinx.html/wiki/Getting-started Include the kotlinx-html-jvm dependency for server-side Kotlin projects using Gradle with Kotlin DSL. ```kotlin dependencies { //Fill this in with the version of kotlinx in use in your project val kotlinxHtmlVersion = "your_version_here" // include for JVM target implementation("org.jetbrains.kotlinx:kotlinx-html-jvm:$kotlinxHtmlVersion") // include for JS target implementation("org.jetbrains.kotlinx:kotlinx-html-js:$kotlinxHtmlVersion") // include for Common module implementation("org.jetbrains.kotlinx:kotlinx-html:$kotlinxHtmlVersion") } ``` -------------------------------- ### Complete HTML Page Template Generation in Kotlin Source: https://context7.com/kotlin/kotlinx.html/llms.txt Generates a full HTML page including head, body, navigation, forms, and scripts using kotlinx.html DSL. This function creates a dynamic page structure based on input parameters like title and username. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML fun generatePage(title: String, username: String?): String = createHTML().html { lang = "en" head { meta(charset = "UTF-8") meta(name = "viewport", content = "width=device-width, initial-scale=1.0") title(title) link(rel = "stylesheet", href = "/css/style.css") style { unsafe { raw(""" .navbar { background: #333; padding: 1rem; } .navbar a { color: white; margin-right: 1rem; } .container { max-width: 1200px; margin: 0 auto; padding: 2rem; } .card { border: 1px solid #ddd; padding: 1rem; margin: 1rem 0; } """) } } } body { // Navigation nav(classes = "navbar") { a(href = "/") { +"Home" } a(href = "/about") { +".About" } a(href = "/contact") { +".Contact" } if (username != null) { span { +".Welcome, $username" } a(href = "/logout") { +".Logout" } } else { a(href = "/login") { +".Login" } } } // Main content div(classes = "container") { h1 { +title } // Dynamic content based on user if (username != null) { div(classes = "card") { h3 { +".Your Dashboard" } p { +".Last login: Today at 10:30 AM" } } } // Contact form div(classes = "card") { h3 { +".Contact Us" } form { action = "/contact" method = FormMethod.post div { label { htmlFor = "name"; +".Name:" } textInput(name = "name") { id = "name"; required = true } } div { label { htmlFor = "email"; +".Email:" } emailInput(name = "email") { id = "email"; required = true } } div { label { htmlFor = "message"; +".Message:" } textArea { id = "message"; name = "message"; rows = "5" } } submitInput { value = "Send Message" } } } } // Footer footer { p { +".Copyright 2024. All rights reserved." } } // Scripts script(src = "/js/app.js") {} } } // Generate the page val pageHtml = generatePage("Welcome to My Site", "john_doe") ``` -------------------------------- ### Build DOM Tree with WasmJs Source: https://github.com/kotlin/kotlinx.html/blob/master/README.md Use this snippet to build a DOM tree for WasmJs-targeted Kotlin applications. It requires importing kotlinx.browser and kotlinx.html modules. ```kotlin import kotlinx.browser.document import kotlinx.browser.window import kotlinx.html.a import kotlinx.html.div import kotlinx.html.dom.append import kotlinx.html.dom.create import kotlinx.html.p fun main() { val body = document.body ?: error("No body") body.append { div { p { +"Here is " a("https://kotlinlang.org") { + "official Kotlin site" } } } } val timeP = document.create.p { +"Time: 0" } body.append(timeP) var time = 0 window.setInterval({ time++ timeP.textContent = "Time: $time" return@setInterval null }, 1000) } ``` -------------------------------- ### Original Dropdown Structure Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing This is the initial, more verbose way to create a dropdown using Twitter Bootstrap components before applying DSL customization. ```kotlin li { classes = setOf("dropdown") a("#", null) { classes = setOf("dropdown-toggle") attributes["data-toggle"] = "dropdown" role = "button" attributes["aria-expanded"] = "false" ul { classes = setOf("dropdown-menu") role = "menu" li { a("#") { + Action" } } li { a("#") { + Another action" } } li { a("#") { + Something else here" } } li { classes = setOf("divider")} li { classes = setOf("dropdown-header"); + Nav header" } li { a("#") { + Separated link" } } li { a("#") { + One more separated link" } } } span { classes = setOf("caret") } } } ``` -------------------------------- ### Defining a Custom HTML Tag Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing Shows how to define a new custom HTML tag, `CUSTOM`, by extending `HTMLTag` and specifying its properties like `inlineTag` and `emptyTag`. ```kotlin class CUSTOM(consumer: TagConsumer<*>) : HTMLTag("custom", consumer, emptyMap(), inlineTag = true, emptyTag = false), HtmlInlineTag { } ``` -------------------------------- ### Create a DIV Element with kotlinx.html Source: https://github.com/kotlin/kotlinx.html/wiki/DOM-trees Use this to create a DOM element instance. Note that this does not append the element to the document. The return type is HTMLElement. ```kotlin import kotlinx.html.* import kotlinx.html.dom.* val myDiv = document.create.div { p { +"text inside" } } ``` -------------------------------- ### Add kotlinx.html JS Dependency for Maven Source: https://github.com/kotlin/kotlinx.html/wiki/Getting-started Add the kotlinx-html-js dependency for client-side (JavaScript) development using Maven. ```xml org.jetbrains.kotlinx kotlinx-html-js ${kotlinx.html.version} ``` -------------------------------- ### Handling Custom and Predefined Target Attributes Source: https://github.com/kotlin/kotlinx.html/wiki/Enum-attributes For attributes like `target` that can have both custom string values and predefined constants, use the `String` type and available constants like `ATarget.blank`. ```kotlin a(target = "myCustomValue") { + "..." } ``` ```kotlin a(target = ATarget.blank) { + "...." } ``` -------------------------------- ### Configure Maven WAR Plugin for JavaScript Overlays Source: https://github.com/kotlin/kotlinx.html/wiki/Getting-started Configure the Maven WAR plugin to include JavaScript files from webjars, such as kotlinx-html-assembly. ```xml org.apache.maven.plugins maven-war-plugin 2.6 META-INF/*,META-INF/**/*,*meta.js,**/*class src/main/resources/web.xml src/main/webapp org.jetbrains.kotlin kotlin-js-library jar kotlin.js js/ org.jetbrains.kotlinx kotlinx-html-assembly webjar jar js/ ``` -------------------------------- ### Import Injector Extensions in Kotlin Source: https://github.com/kotlin/kotlinx.html/wiki/Injector Import the necessary injector extensions for use in your Kotlin project. ```kotlin import kotlinx.html.injector.* ``` -------------------------------- ### Extension Functions for Dropdown Components Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing Provides additional extension functions like `dropdownToggle`, `dropdownMenu`, `dropdownHeader`, and `divider` to further abstract and simplify dropdown creation. ```kotlin fun LI.dropdownToggle(block : A.() -> Unit) { a("#", null, "dropdown-toggle") { attributes["data-toggle"] = "dropdown" role = "button" attributes["aria-expanded"] = "false" block() span { classes = setOf("caret") } } } ``` ```kotlin fun LI.dropdownMenu(block : UL.() -> Unit) : Unit = ul("dropdown-menu") { role = "menu" block() } ``` ```kotlin fun UL.dropdownHeader(text : String) : Unit = li { classes = setOf("dropdown-header"); +text } fun UL.divider() : Unit = li { classes = setOf("divider")} ``` -------------------------------- ### Stream HTML with appendHTML Source: https://context7.com/kotlin/kotlinx.html/llms.txt Use appendHTML() to stream HTML generation directly to output streams like System.out or StringBuilder. This is memory-efficient for large pages. ```kotlin import kotlinx.html.* import kotlinx.html.stream.appendHTML // Stream to stdout System.out.appendHTML().html { body { div { a("https://kotlinlang.org") { target = ATarget.blank +"Main site" } } } } ``` ```kotlin // Build with StringBuilder val text = buildString { appendLine("") appendHTML().html { body { a("http://kotlinlang.org") { +"link" } } } appendLine() } ``` ```kotlin // Write directly to a file java.io.File("output.html").writer().use { writer -> writer.appendHTML().html { body { h1 { +"Generated Page" } } } } ``` -------------------------------- ### Custom HTML DSL with Extension Functions Source: https://context7.com/kotlin/kotlinx.html/llms.txt Define extension functions on tag types to create reusable components and domain-specific abstractions over the HTML DSL. This promotes code organization and maintainability for complex UIs. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML // Bootstrap card component fun FlowContent.card(title: String, block: DIV.() -> Unit) { div(classes = "card") { div(classes = "card-header") { h5(classes = "card-title") { +title } } div(classes = "card-body") { block() } } } // Bootstrap alert component fun FlowContent.alert(type: String = "info", block: DIV.() -> Unit) { div(classes = "alert alert-$type") { attributes["role"] = "alert" block() } } // Bootstrap dropdown fun UL.dropdown(text: String, block: UL.() -> Unit) { li(classes = "dropdown") { a(href = "#", classes = "dropdown-toggle") { attributes["data-toggle"] = "dropdown" +text span(classes = "caret") {} } ul(classes = "dropdown-menu") { block() } } } // Icon helper fun FlowOrPhrasingContent.icon(name: String) { i(classes = "fa fa-$name") {} } // Usage val html = createHTML().div(classes = "container") { alert("success") { icon("check") +" Operation completed successfully!" } card("User Profile") { p { + ``` ```kotlin Name: John Doe" } p { + ``` ```kotlin Email: john@example.com" } button(classes = "btn btn-primary") { icon("edit") +" Edit Profile" } } ul(classes = "nav") { dropdown("Menu") { li { a(href = "#action1") { + ``` ```kotlin Action" } } li { a(href = "#action2") { + ``` ```kotlin Another action" } } li(classes = "divider") {} li { a(href = "#action3") { + ``` ```kotlin Separated link" } } } } } ``` -------------------------------- ### Injecting Unsafe HTML Content Source: https://context7.com/kotlin/kotlinx.html/llms.txt Use the `unsafe` block to insert raw HTML, including inline scripts and styles, without escaping. Exercise caution to prevent XSS vulnerabilities. This is necessary for dynamic content that cannot be represented by the DSL alone. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML val html = createHTML().html { head { // Inline styles style { unsafe { raw(""" body { background-color: #f5f5f5; font-family: Arial, sans-serif; } .container { max-width: 1200px; margin: 0 auto; } """) } } // Inline JavaScript script(type = ScriptType.textJavaScript) { unsafe { raw(""" function greet(name) { alert('Hello, ' + name + '!'); } document.addEventListener('DOMContentLoaded', function() { console.log('Page loaded'); }); """) } } } body { div(classes = "container") { button { onClick = "greet('World')" +"Greet" } } // External script script(src = "https://cdn.example.com/library.js") {} } } ``` -------------------------------- ### Define and Use Custom HTML Tags in Kotlin Source: https://context7.com/kotlin/kotlinx.html/llms.txt Learn to create custom HTML tags by extending HTMLTag and defining builder functions. This allows for reusable, custom elements within your HTML structure. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML // Define custom tag class class CUSTOM( initialAttributes: Map, consumer: TagConsumer<*>) : HTMLTag( tagName = "custom-element", consumer = consumer, initialAttributes = initialAttributes, namespace = null, inlineTag = false, emptyTag = false ), FlowContent { // Custom attribute var customAttr: String get() = attributes["custom-attr"] ?: "" set(value) { attributes["custom-attr"] = value } } // Extension for use inside DIV fun DIV.customElement( classes: String? = null, block: CUSTOM.() -> Unit = {} ) { CUSTOM( attributesMapOf("class", classes), consumer ).visit(block) } // Extension for root-level usage fun TagConsumer.customElement( classes: String? = null, block: CUSTOM.() -> Unit = {} ): T { return CUSTOM( attributesMapOf("class", classes), this ).visitAndFinalize(this, block) } // Usage val html = createHTML(prettyPrint = false).div { customElement(classes = "widget") { customAttr = "my-value" span { + ``` ```kotlin Content inside custom element" } } // Output:
Content inside custom element
``` -------------------------------- ### Measure HTML Generation Time Source: https://context7.com/kotlin/kotlinx.html/llms.txt Measure the performance of HTML generation using the measureTime interceptor. This helps in identifying performance bottlenecks in complex HTML structures. ```kotlin import kotlinx.html.* import kotlinx.html.stream.* import kotlinx.html.consumers.* // Measure generation time System.out.appendHTML().measureTime().html { head { title("Performance Test") } body { repeat(1000) { i -> div { + ``` ```kotlin "Item $i" } } }.let { result -> println() println("Generated in ${result.time} ms") } ``` -------------------------------- ### Setting Element Attributes in Kotlin HTML DSL Source: https://context7.com/kotlin/kotlinx.html/llms.txt Shows how to set standard HTML attributes as properties and custom data attributes using the `attributes` map. Utilizes type-safe enum constants for predefined attributes. ```kotlin import kotlinx.html.* import kotlinx.html.stream.createHTML val html = createHTML(prettyPrint = false).div { // Standard attributes as properties a { href = "https://example.com" target = ATarget.blank // Type-safe constant rel = "noopener noreferrer" +("External Link") } // Image with attributes img { src = "/images/photo.jpg" alt = "Photo description" width = "300" height = "200" } // Form with enum attributes form { action = "/submit" method = FormMethod.post encType = FormEncType.multipartFormData input { type = InputType.text name = "username" placeholder = "Enter username" required = true } } // Custom data attributes div { id = "myElement" attributes["data-toggle"] = "modal" attributes["data-target"] = "#myModal" attributes["aria-expanded"] = "false" +("Click me") } } ``` -------------------------------- ### Apply CSS Classes During Element Creation Source: https://github.com/kotlin/kotlinx.html/wiki/Elements-CSS-classes Use the optional 'classes' argument in element builder functions to set a space-separated string of CSS classes when creating an element. ```kotlin div(classes = "container left tree") { } ``` -------------------------------- ### Measure HTML Generation Time Source: https://github.com/kotlin/kotlinx.html/wiki/Interceptors Utilize the measureTime interceptor to record the time taken for HTML generation. This is useful for performance analysis. ```kotlin System.out.appendHTML().measureTime().html { head { title("Welcome page") } body { div { +("<<>>") } div { CDATA("Here is my content") } } }.let { println() println("Generated in ${it.time} ms") } ``` -------------------------------- ### Append a DIV to an Existing Element with kotlinx.html Source: https://github.com/kotlin/kotlinx.html/wiki/DOM-trees Use the `append` function to add a newly created DOM tree as a child to an existing node. This is useful for dynamically updating the UI. ```kotlin fun appendTab(containerDiv: HTMLDivElement) { containerDiv.append.div { p { +"tab" } div { //... } } } ``` -------------------------------- ### Append HTML within StringBuilder Source: https://github.com/kotlin/kotlinx.html/wiki/Streaming Demonstrates using appendHTML to generate HTML content directly within a StringBuilder lambda. Includes basic HTML structure with a link. ```kotlin val text = buildString { appendLine("") appendHTML().html { body { a("http://kotlinlang.org") { + "link" } } } appendLine() } ``` -------------------------------- ### Handle Click Event with Lambda in JS Source: https://github.com/kotlin/kotlinx.html/wiki/Events Use `onClickFunction` to specify a lambda for event handling in DOM mode for JS targets. Ensure `kotlinx.html.js.*` is imported. This property is only available in JS. ```kotlin div { onClickFunction = { event -> window.alert("Kotlin!") } } ``` -------------------------------- ### Registering Custom Tag on Root Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing Extends `TagConsumer` to make the custom `CUSTOM` tag available for use at the root level of the HTML structure. ```kotlin fun TagConsumer.custom(block: CUSTOM.() -> Unit = {}): T { return CUSTOM(this).visitAndFinalize(this, block) } ``` -------------------------------- ### Extension Function for Dropdown Source: https://github.com/kotlin/kotlinx.html/wiki/Micro-templating-and-DSL-customizing Defines a top-level extension function `dropdown` for the `UL` tag to simplify the creation of dropdown list items. ```kotlin fun UL.dropdown(block : LI.() -> Unit) { li("dropdown") { block() } } ``` -------------------------------- ### Standard Input Field Declaration Source: https://github.com/kotlin/kotlinx.html/wiki/Enum-attributes Declare input fields using the `input` tag with explicit `type` and `name` attributes. This can become verbose with many fields. ```kotlin form(action = "/form", encType = FormEncType.multipartFormData, method = FormMethod.post) { input(type = InputType.text, name = "field1") input(type = InputType.text, name = "field2") input(type = InputType.checkBox, name = "field3") input(type = InputType.text, name = "field4") input(type = InputType.file, name = "field5") input(type = InputType.text, name = "field6") } ``` -------------------------------- ### Embed Raw CSS in Style Tag Source: https://github.com/kotlin/kotlinx.html/wiki/Style-and-script-tags Use `unsafe { raw { ... } }` to embed unescaped CSS content within a `