Skip to content

Instantly share code, notes, and snippets.

@trenthudy
Last active September 30, 2021 18:21
Show Gist options
  • Save trenthudy/8267ec03048b66439bb9469ae9444cec to your computer and use it in GitHub Desktop.
Save trenthudy/8267ec03048b66439bb9469ae9444cec to your computer and use it in GitHub Desktop.
package io.hudepohl
import java.lang.StringBuilder
class Html {
private val value: StringBuilder = StringBuilder()
private fun add(text: String) = value.append(text)
override fun toString(): String = value.toString()
fun html(htmlTags: Html.() -> Unit) {
val innerHtml = Html().apply { htmlTags() }.toString()
add("<html>$innerHtml</html>")
}
fun body(htmlTags: Html.() -> Unit) {
val innerHtml = Html().apply { htmlTags() }.toString()
add("<body>$innerHtml</body>")
}
fun div(style: String, htmlTags: Html.() -> Unit) {
val innerHtml = Html().apply { htmlTags() }.toString()
add("<div style=\"$style\">$innerHtml</div>")
}
fun table(
hasBorder: Boolean = false,
widthPercent: Int = 100,
cellPadding: Int = 5,
style: String,
htmlTags: Html.() -> Unit
) {
val borderTxt = "border=\"${if (hasBorder) "1" else "0"}\""
val widthTxt = "width=\"$widthPercent%\""
val cellPaddingTxt = "cellpadding=\"$cellPadding\""
val innerHtml = Html().apply { htmlTags() }.toString()
add("<table $borderTxt $widthTxt $cellPaddingTxt style=\"$style\">$innerHtml</table>")
}
fun tr(htmlTags: Html.() -> Unit) {
val innerHtml = Html.fromTags(htmlTags)
add("<tr>$innerHtml</tr>")
}
fun center(htmlTags: Html.() -> Unit) {
val innerHtml = Html().apply { htmlTags() }.toString()
add("<center>$innerHtml</center>")
}
fun th(style: String, value: String) {
val styleTxt = "style=\"$style\""
add("<th $styleTxt>$value</th>")
}
fun td(style: String, value: String) {
val styleTxt = "style=\"$style\""
add("<td $styleTxt>$value</td>")
}
fun h1(lineText: String) = add("<h1>$lineText</h1>")
fun h2(lineText: String) = add("<h2>$lineText</h2>")
fun h3(lineText: String) = add("<h3>$lineText</h3>")
fun h4(lineText: String) = add("<h4>$lineText</h4>")
fun h5(lineText: String) = add("<h5>$lineText</h5>")
fun h6(lineText: String) = add("<h6>$lineText</h6>")
fun p(lineText: String) = add("<p>$lineText</p>")
fun br() = add("<br>")
fun hr() = add("<hr />")
companion object {
fun fromTags(htmlTags: Html.() -> Unit): String = Html().apply { htmlTags() }.toString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment