kotlinx.html
kotlinx.html copied to clipboard
There is no attribute "id" in any tag definition
Actual workaround :
div(.....) {
attributes["id"] = "special-div"
}
Expected api :
div(id = "special-div".....) {}
div {
id = "special-div"
}
In fact id is not so frequently used to provide it in every function as an optional parameter however the corresponding attribute is always available so there is no need to use attributes map
Hi, just had a similar confusion and came up with this helper function for divs which allows specifying arbitrary attributes:
import org.testng.annotations.Test
import kotlinx.html.*
import kotlinx.html.stream.appendHTML
import java.io.StringWriter
import kotlin.test.assertEquals
object HTMLTest {
fun FlowContent.div(classes: String = "", vararg attributes: Pair<String, String>, block: FlowContent.() -> Unit) {
val attributeMap = attributes.toList()
.plus("class" to classes)
.associate { it }
DIV(attributeMap, consumer).visit(block)
}
@Test
fun `test html with attribute list`(){
val stringWriter = StringWriter()
stringWriter.appendHTML().html {
body {
div ("main", "id" to "main-body", "style" to "float: left") {
text("main")
}
}
}
assertEquals("""
<html>
<body>
<div id="main-body" style="float: left" class="main">main</div>
</body>
</html>""".trim(), stringWriter.toString().trim())
}
}
What do you think? I find the pattern a bit more intuitive (especially for people less familiar with Kotlin) than accessing fields of the tag object via extension method magic.
@Tatskaari
I think that your proposal is very good as it approaches the original way of writing HTML.
I think that it is better to include classes in attributes as well as how to write HTML more.
I am currently converting the templates for a large website to kotlinx.html. Those templates are using id and also class attributes a lot. Being able to add classes as a parameter but not the id, feels very inconsistent and unsexy.
In a new project I would try to minimize using id attributes, hence this will not be a big issue. But for converting existing projects, it is a big pain.
@cy6erGn0m Agreed with the above devs. I use ids all the time, and having to declare them as part of the builder instead of in the tag function is inconsistent. Ideally there would be an optional parameter that I could use:
section(id = "aboutSection") {
}
Over the past several weeks, I've created an alternative library, kotlin-html to remedy pain points of kotlinx.html that I've found like this; primarily to add css, provide first-class support for ids, classes, and styles, and provide a simpler architecture so it's easier for people to contribute.