Skip to content

Instantly share code, notes, and snippets.

@retronym
Created December 20, 2009 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retronym/260446 to your computer and use it in GitHub Desktop.
Save retronym/260446 to your computer and use it in GitHub Desktop.
Immutable HTML Builder
import xml.{Text, Node, NodeSeq}
class HtmlBuilder {
var html: NodeSeq = NodeSeq.Empty
def b(f: (HtmlBuilder) => Seq[Node]): Node = <b>{f(this).toSeq}</b>
def a(href: String)(f: (HtmlBuilder) => Seq[Node]): Node = <a href={href}>{f(this).toSeq}</a>
def text(text: String): Text = Text(text)
}
val builder: HtmlBuilder = new HtmlBuilder
import builder._
val html = a(href = "http://scala-lang.org") { builder => import builder._; Seq(
b { builder => Seq(
text("Scala Lang Website")
)}
)}
assert(html.toString == """<a href="http://scala-lang.org"><b>Scala Lang Website</b></a>""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment