How do you turn a kotlinx.html widget into a string?

422 Views Asked by At

In the kotlinx.html documentation, it talks building "widgets" (where a widget is just some of the html dsl) like this:

@HtmlTagMarker
fun FlowContent.widget(body: FlowContent.() -> Unit) {
  div { body() }
}

How would you turn that into html if you didn't want to wrap it in a body? It's clear how you would get it wrapped in something else:

createHTML().body {
  widget { +"stuff" }
}

gets you

<body>
  <div>stuff</div>
</body>

But what's the right way to just get the <div>stuff</div> without wrapping it in something?

1

There are 1 best solutions below

0
On

According to (not-so-easy-to-discover) official documentation:

If you want it to be available on the root (like this: appendHTML().custom { }) you have to declare it on TagConsumer

So to make your example work you need:

fun <T> TagConsumer<T>.widget(block: FlowContent.() -> Unit): T =
    div { block() }

And using it will give you expected result:

val html = createHTML()
    .widget { +"Hello" }
    .toString()

assert html == "<div>Hello</div>"