I'm using kotlinx.html's DSL to create HTML, and I need references to some of the elements created (to refer to them in event handlers etc.). However, while the functions used directly within the block passed to Node.append
do return references to the elements they create, it seems similar functions called within them to create nested elements do not.
Example code:
fun Node.appendElements() {
append {
val outer = div { // works as expected
val inner = div {} // does not work
}
}
}
Note that outer
indeed refers to the newly created and appended outer div
created directly in the append
block (this is basically the scenario of When using kotlinx.html's DSL to create HTML, (how) is it possible to refer to the created elements?), but the div
called within that div
(in the nested block, not directly in the append
) returns Unit
, so that same (or at least very similar) solution doesn't work for the inner div
(or generally for nested elements created not directly in the append
block, but within blocks used to create outer elements).
I ended up writing a much more cumbersome code, similar to the following:
fun Node.appendElements() {
append {
val outer = div {}
outer.append {
val inner = div {}
}
}
}
That works, but is much less elegant. Is there any better / more idiomatic way to achieve this?