2

In Kotlin page, under HTML-Builder I can see the below code, how can I use it in simple .tk file? how t get started here?

val data = mapOf(1 to "one", 2 to "two")

createHTML().table {
    for ((num, string) in data) {
Iterate over data
        tr {
Functions to create HTML tags
           td { +"$num" } 
           td { +string }
        }
    }
}
Hasan A Yousef
  • 22,789
  • 24
  • 132
  • 203
  • Your link doesn't even point to the Koans. You're looking for [this one](https://try.kotlinlang.org/#/Kotlin%20Koans/Builders/Html%20builders/Task.kt). But notice the [html.kt](https://try.kotlinlang.org/#/Kotlin%20Koans/Builders/Html%20builders/html.kt) file on the left. – chris Sep 25 '17 at 20:27
  • That example I think comes from the Koans, but you might be looking for [the `kotlinx.html` library](https://github.com/Kotlin/kotlinx.html). – mkobit Sep 25 '17 at 20:43
  • @chris still did not get how to make it, there is no 'main' function, how to call this, and h how it will be displayed. – Hasan A Yousef Sep 26 '17 at 01:56
  • @mkobit still did not get how to use it, can you provide full example, thanks – Hasan A Yousef Sep 26 '17 at 01:57
  • @HasanAYousef, Yeah, the html.kt file is essentially a small library. The entry points are the tests in the other file, which call `renderProductTable`. That gives a pretty clear view of how to use it. – chris Sep 26 '17 at 04:38

1 Answers1

8

You’re referring to a DSL written in Kotlin for constructing HTML through the builder. The library can be found here: https://github.com/Kotlin/kotlinx.html

Here's a running example:

fun main(args: Array<String>) {
    val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
    val html = document.create.html {
        head {
            title("Hello world")
        }
        body {
            h1("h1Class"){
                +"My header1"
            }
            p("pClass"){
                +"paragraph1"
            }
        }
    }

   intoStream(html, System.out)
}

fun intoStream(doc: Element, out: OutputStream) {
    with(TransformerFactory.newInstance().newTransformer()){
        setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no")
        setOutputProperty(OutputKeys.METHOD, "xml")
        setOutputProperty(OutputKeys.INDENT, "yes")
        setOutputProperty(OutputKeys.ENCODING, "UTF-8")
        setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
        transform(DOMSource(doc),
                StreamResult(OutputStreamWriter(out, "UTF-8")))
    }
}

And finally here's the corresponding output:

<?xml version="1.0" encoding="UTF-8"?><html>
<head>
    <title>Hello world</title>
</head>
<body>
    <h1 class="h1Class">My header1</h1>
    <p class="pClass">paragraph1</p>
</body>
</html>
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196