// Created on savesnippets.com ยท https://savesnippets.com/KQ17madklqYjOy @DslMarker annotation class HtmlDsl @HtmlDsl class Tag(val name: String) { val children = mutableListOf() val attributes = mutableMapOf() var text: String? = null fun render(): String = buildString { append("<$name") attributes.forEach { (k, v) -> append(" $k=\"$v\"") } append(">") text?.let { append(it) } children.forEach { append(it.render()) } append("") } } fun html(block: Tag.() -> Unit): Tag = Tag("html").apply(block) fun Tag.body(block: Tag.() -> Unit): Tag = Tag("body").apply(block).also { children.add(it) } fun Tag.h1(text: String) { children += Tag("h1").apply { this.text = text } } fun Tag.p(text: String) { children += Tag("p").apply { this.text = text } } fun main() { val page = html { body { h1("Hello, world") p("Welcome to my page.") } } println(page.render()) //

Hello, world

Welcome to my page.

}