https://kotlinlang.org logo
Title
j

jdelaney

09/23/2019, 2:59 PM
👋 With
kotlinx.html
, is there a way to apply a class to all children of a tag? e.g. if I have
fun BODY.card(block: DIV.() -> Unit = {}) {
    div("card") {
        // I want to apply the "section" class to 
        // the top-level tags here
        block()
    }
}
https://github.com/kotlin/kotlinx.html/wiki/Interceptors mentions the ability to transform some HTML but doesn't actually say how. (I know this isn't best practice for CSS but I'm trying to make some generic functions for a CSS framework I'm using)
s

Soren Valle

09/23/2019, 3:22 PM
I am not aware of a standard way. I'd have to look at the receiver of the builder, but I would imagine on execution of the tag lambda it is added to a child collection of some type on the receiver. Which would mean it's children would also be. If so you could potentially write your own extension function on the receiver that adds a class to all the children. I'm making a lot of assumptions since I can't look at any code right now, but it might be worth taking a look. I'll try to get into it more later.
j

jdelaney

09/23/2019, 3:28 PM
Thanks @Soren Valle 🙂
👍 1
s

Soren Valle

09/23/2019, 10:33 PM
So it turns out the builder construct is not as clear to me as I thought it would be having read some docs about it (or something related to it) in the past else where. So without some work on my part I'm not able to tell you a way to build it in. That being said an easy, albeit a a bit manual solution, is as follows
iimport kotlinx.html.DIV
import kotlinx.html.div
import kotlinx.html.dom.append
import kotlin.browser.document
import kotlin.browser.window

fun DIV.card(block: (DIV.(classes: String) -> Unit)? = null) {
    div("card") {
        +"Card"
        block?.let { it("section") }
    }
}

fun main() {

    window.onload = {

        document.getElementById("root")!!.append {
            div {
                +"Card Consumer"
                card { classes ->
                    div(classes) {
                        +"Section 1"
                    }
                    div(classes) {
                        +"Section 2"
                    }
                    div(classes) {
                        +"Section 3"
                    }
                }
            }
        }
    }
}
j

jdelaney

09/24/2019, 1:25 AM
I'll give that a shot, thank you so much for looking into this!