Skip to content

Instantly share code, notes, and snippets.

@sxross
Created May 27, 2011 21:06
Show Gist options
  • Save sxross/996166 to your computer and use it in GitHub Desktop.
Save sxross/996166 to your computer and use it in GitHub Desktop.
Coffeescript HTML Tag Helper Class
# HTML Tag class
#
# Purpose: Programmatically generate HTML so you aren't scotch-taping
# strings together all the time.
#
# Usage: targetString = Tag.make(tagName, attributeHash, text)
#
# Where: targetString: is what you will eventually inject into the DOM -- the HTML
# tagName: is the actual tag name (i.e., "tr" or "input")
# attributeHash: is the set of tag attributes, for example --
# class: "even-row", id: "row#{indexVar}", title: "Yo, Dog!"
# Note that repeating hash keys is a BAD idea. so:
# class: "even-row", class: "zebra-stripe"
# will not do what you expect. It works on the "last one wins"
# principle. Instead, use:
# class: "even-row zebra-stripe"
# text: is the text enclosed in the tag. If it is a self-closing
# tag like img or input, then leave the text empty.
class Tag
@make: (tagName, attributes, text...) ->
t = new Tag
t.name = tagName
t.attributes = attributes
t.text = ''
t.text = text.join('')
t
openTag: ->
attributeStrings = []
close = null
unless @text
close = ' />'
else
close = '>'
attributeStrings.push("#{key}=\"#{attribute}\"") for key, attribute of @attributes when key != 'text'
attributeString = if attributeStrings.length > 0 then ' ' + attributeStrings.join(' ') else ''
"<#{@name}#{attributeString}#{close}"
closeTag: (name) ->
"</#{@name}>"
tag: ->
parts = [@openTag()]
parts.push @text
parts.push @closeTag() if @text.length > 0
parts.join('')
toString: ->
@tag()
# Example
t = Tag.make('table', null,
Tag.make('tr', class: 'animals', id: 'dog',
Tag.make('th', null, 'animal name')
Tag.make('td', {}, Tag.make('input', type: 'text'))
)
)
console.log t.tag()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment