Created
November 22, 2011 03:36
-
-
Save maxp/1384821 to your computer and use it in GitHub Desktop.
Coffeescript html_renderer
This file contains hidden or 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
| tag = (name, content, attributes) -> | |
| name: name | |
| attributes: attributes | |
| content: content | |
| htmlDoc = (title, bodyContent) -> | |
| tag "html", [tag("head", [tag "title", [title]]), | |
| tag "body", bodyContent] | |
| | |
| escapeHTML = (text) -> | |
| replacements = [[/&/g, ’&’] | |
| [/"/g, ’"’] | |
| [/</g, ’<’] | |
| [/>/g, ’>’]] | |
| forEach replacements, (replace) -> | |
| text = text.replace replace[0], replace[1] | |
| text | |
| renderHTML = (element) -> | |
| pieces = [] | |
| | |
| renderAttributes = (attributes) -> | |
| result = [] | |
| if attributes | |
| for name of attributes | |
| result.push ' ' + name + '="' + | |
| escapeHTML(attributes[name]) + '"' | |
| result.join '' | |
| | |
| render = (element) -> | |
| # Text node | |
| if typeof element is 'string' | |
| pieces.push escapeHTML element | |
| # Empty tag | |
| else if not element.content or | |
| element.content.length == 0 | |
| pieces.push '<' + element.name + | |
| renderAttributes(element.attributes) + '/>' | |
| # Tag with content | |
| else | |
| pieces.push '<' + element.name + | |
| renderAttributes(element.attributes) + '>' | |
| forEach element.content, render | |
| pieces.push '</' + element.name + '>' | |
| | |
| render element | |
| pieces.join '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment