1
\$\begingroup\$

I'm looking to create a library that extends kotlinx.html and will include functions that have default css classes.

The goal is to be able to use a function row{} instead of having to type div(classes = "row"){} each time. I would like to create these functions for a lot more commonly used Bootstrap classes.

In my example I use the DIV class to create a row function

The original div function:

@HtmlTagMarker
fun FlowContent.div(classes : String? = null, block : DIV.() -> Unit = {}) : Unit = DIV(attributesMapOf("class", classes), consumer).visit(block)

The first function I created has the row class set instead of `null.

@HtmlTagMarker
fun FlowContent.row(classes: String? = "row", block: DIV.() -> Unit = {}): Unit = DIV(attributesMapOf("class", classes), consumer).visit(block)

But this seems to be very restrictive, since the user of this function won't be able to add any additional css classes.

Therefore I put the row class in the DIV constructor as a string template. This way it can still be extended.

@HtmlTagMarker
fun FlowContent.row(classes: String? = "", block: DIV.() -> Unit = {}): Unit = DIV(attributesMapOf("class", "row $classes"), consumer).visit(block)

Does this seem like the right approach, or is it better to do this another way.

Update

From the kotlinx.html documentation, I also found this approach.

fun DIV.row(block: DIV.() -> Unit) = div(classes = "row") { block() }

I must say that it looks very clean.

\$\endgroup\$
  • \$\begingroup\$ "Does this seem like the right approach" Did you test it? \$\endgroup\$ – Mast Aug 16 '18 at 16:48
  • 1
    \$\begingroup\$ @Mast I did test it, and it works. but I'm wondering if I'm not taking it too lightly or if I'm overthinking here \$\endgroup\$ – Johan Vergeer Aug 16 '18 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.