@DslMarker annotation class HtmlDsl
@HtmlDsl
class Tag(val name: String) {
val children = mutableListOf<Tag>()
val attributes = mutableMapOf<String, String>()
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("</$name>")
}
}
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())
// <html><body><h1>Hello, world</h1><p>Welcome to my page.</p></body></html>
}
Create a free account and build your private vault. Share publicly whenever you want.