-
Notifications
You must be signed in to change notification settings - Fork 133
Streaming
xavierly edited this page Apr 4, 2021
·
4 revisions
On server side it is common practice to generate pages to an output stream (to a socket through a buffered writer). Also you often actually don't need DOM tree but text representation only. In this case you need streaming.
To start building HTML to any Appendable you can use appendHTML
function with the following look:
fun Appendable.appendHTML(prettyPrint: Boolean = true)
Notice optional argument prettyPrint
: you can switch it to off to get pages smaller
There are many types of Appendable interface but the most popular are StringBuilder, StringWriter, Writer and PrintStream
See example how to generate HTML to stdout
System.out.appendHTML().div {
h1 { +"Heading 1" }
}
If you just need a text you can use shortcut function createHTML
val text = createHTML().div {
// content here
}
As StringBuilder
is Appendable too you can use appendHTML inside StringBuilder lambda:
val text = buildString {
appendLine("<!DOCTYPE html>")
appendHTML().html {
body {
a("http://kotlinlang.org") { +"link" }
}
}
appendLine()
}