This pattern helps you create HTML code easily using Kotlin code. It makes writing HTML fun and less error-prone.
0
0
HTML builder example pattern in Kotlin
Introduction
When you want to generate HTML pages dynamically in Kotlin.
When you want to build HTML content without writing raw strings.
When you want your HTML code to be clear and easy to read in Kotlin.
When you want to reuse HTML parts in your Kotlin programs.
Syntax
Kotlin
fun html(block: Html.() -> Unit): Html { val html = Html() html.block() return html } class Html { fun body(block: Body.() -> Unit) { /*...*/ } override fun toString(): String = "<html>...</html>" } class Body { fun p(text: String) { /*...*/ } }
The block is a lambda with receiver, letting you write nested HTML easily.
Classes like Html and Body represent HTML tags and have functions for child tags.
Examples
This creates an HTML page with a body containing a paragraph with text.
Kotlin
val page = html { body { p("Hello, world!") } }
You can add multiple paragraphs inside the body.
Kotlin
val page = html { body { p("Welcome to Kotlin HTML builder.") p("This is easy to read.") } }
Sample Program
This program builds a simple HTML page with two paragraphs inside the body. It prints the HTML code.
Kotlin
fun html(block: Html.() -> Unit): Html { val html = Html() html.block() return html } class Html { private val children = mutableListOf<String>() fun body(block: Body.() -> Unit) { val body = Body() body.block() children.add(body.toString()) } override fun toString(): String = "<html>\n" + children.joinToString("\n") + "\n</html>" } class Body { private val children = mutableListOf<String>() fun p(text: String) { children.add("<p>$text</p>") } override fun toString(): String = "<body>\n" + children.joinToString("\n") + "\n</body>" } fun main() { val page = html { body { p("Hello, Kotlin HTML builder!") p("This is a simple example.") } } println(page) }
OutputSuccess
Important Notes
You can add more tags by creating more classes like Body with functions for child tags.
This pattern uses Kotlin's lambdas with receivers to make nested HTML easy to write.
Summary
The HTML builder pattern lets you write HTML in Kotlin code clearly and safely.
It uses classes and lambdas to represent HTML tags and their children.
This helps avoid mistakes and makes your HTML code easy to read and maintain.