Skip to content

Instantly share code, notes, and snippets.

@maxp
Created November 22, 2011 03:36
Show Gist options
  • Select an option

  • Save maxp/1384821 to your computer and use it in GitHub Desktop.

Select an option

Save maxp/1384821 to your computer and use it in GitHub Desktop.
Coffeescript html_renderer
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, ’&lt;’]
[/>/g, ’&gt;’]]
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