Builder can generate tags with attributes.

This commit is contained in:
Nathan Sobo
2011-12-27 16:16:35 -06:00
parent b5a06c288e
commit 21fb88141e
3 changed files with 21 additions and 5 deletions

View File

@@ -29,3 +29,9 @@ fdescribe "Builder", ->
builder.tag 'div', 22
expect(builder.toHtml()).toBe("<div>22</div>")
it "can generate tags with attributes", ->
builder.tag 'div', id: 'foo', class: 'bar'
fragment = builder.toFragment()
expect(fragment.attr('id')).toBe('foo')
expect(fragment.attr('class')).toBe('bar')

View File

@@ -1,4 +1,5 @@
_ = require 'underscore'
$ = require 'jquery'
OpenTag = require 'template/open-tag'
CloseTag = require 'template/close-tag'
Text = require 'template/text'
@@ -11,9 +12,12 @@ class Builder
toHtml: ->
_.map(@document, (x) -> x.toHtml()).join('')
toFragment: ->
$(@toHtml())
tag: (name, args...) ->
options = @extractOptions(args)
@openTag(name)
@openTag(name, options.attributes)
options.content?()
@text(options.text) if options.text
@closeTag(name)
@@ -24,10 +28,11 @@ class Builder
options.content = arg if _.isFunction(arg)
options.text = arg if _.isString(arg)
options.text = arg.toString() if _.isNumber(arg)
options.attributes = arg if _.isObject(arg)
options
openTag: (name) ->
@document.push(new OpenTag(name))
openTag: (name, attributes) ->
@document.push(new OpenTag(name, attributes))
closeTag: (name) ->
@document.push(new CloseTag(name))

View File

@@ -1,7 +1,12 @@
_ = require 'underscore'
module.exports =
class OpenTag
constructor: (@name) ->
constructor: (@name, @attributes) ->
toHtml: ->
"<#{@name}>"
"<#{@name}#{@attributesHtml()}>"
attributesHtml: ->
s = _.map(@attributes, (value, key) -> "#{key}=\"#{value}\"").join(' ')
if s == "" then "" else " " + s