Skip to content

Instantly share code, notes, and snippets.

@akx
Created January 9, 2013 12:01
Show Gist options
  • Save akx/4492623 to your computer and use it in GitHub Desktop.
Save akx/4492623 to your computer and use it in GitHub Desktop.
Fun with DSLs, Coco style.
X = (tag, content=null, attrs={}, parent=null) ->
if content and typeof content != "string" => attrs = content; content = null
node = ({tag, content, attrs}) => parent?@@children.push &
((tag, content=null, attrs={}) -> X tag, content, attrs, node) => &node=node
render = (node, emit=console.log, indent=0) ->
node = node?.node || node
empty = true unless node.content or node.children
idt = (" " * indent)
emit idt + "<#{node.tag}" + (" #key=\"#value\"" for key, value in node.attrs || {}) + (if empty then "/>" else ">")
if node.content then emit that
if node.children then
emit "\n"
for node.children => render &, emit, indent + 1
emit idt
emit (if not empty then "</#{node.tag}>" else "") + "\n"
write = (node) ->
render root, (out = []).~push
console.log out.join ""
##############################################################################################################################
root = X "foo"
& "bar", {baz: "quux"}
& "derp", "and some content"
& "nested"
& "nested-too"
write root
<foo>
<bar baz="quux"/>
<derp>and some content
<nested/>
<nested-too/>
</derp>
</foo>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment