2017-09-25 73 views
0

Kotlin page,在HTML-Builder下我可以看到下面的代碼,我怎樣才能在簡單的.tk文件中使用它?這裏怎麼開始?Kotlin HTML-Builder

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 } 
     } 
    } 
} 
+0

您的鏈接甚至不指向Koans。你正在尋找[這一個](https://try.kotlinlang.org/#/Kotlin%20Koans/Builders/Html%20builders/Task.kt)。但請注意左側的[html.kt](https://try.kotlinlang.org/#/Kotlin%20Koans/Builders/Html%20builders/html.kt)文件。 – chris

+0

我認爲這個例子來自Koans,但您可能正在尋找[kotlinx.html'庫(https://github.com/Kotlin/kotlinx.html))。 – mkobit

+0

@chris仍然沒有得到如何製作,沒有「主要」功能,如何調用它,以及如何顯示它。 –

回答

2

你指的是DSL 在科特林通過建設者構建HTML。這個庫可以在這裏找到:https://github.com/Kotlin/kotlinx.html

這裏是一個正在運行的例子:

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"))) 
    } 
} 

最後,這裏的相應的輸出:

<?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> 
+0

仍然沒有得到如何使它,你能提供完整的例子,謝謝。 –

+0

我添加了一個示例 – s1m0nw1

+0

謝謝,你能幫助這裏:https://stackoverflow.com/questions/46455185/handling-freemaker-template-with-ktor-kotlin –