Created
January 9, 2013 12:01
-
-
Save akx/4492623 to your computer and use it in GitHub Desktop.
Fun with DSLs, Coco style.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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