Permalink
Browse files

HTML5 data attribute helpers [#5825 state:resolved].

  • Loading branch information...
1 parent 67df21f commit 5e79094fc1dbb62e27cf21c0f18b586a26d5de46 @stephencelis stephencelis committed with NZKoz Oct 17, 2010
Showing with 24 additions and 4 deletions.
  1. +17 −4 actionpack/lib/action_view/helpers/tag_helper.rb
  2. +7 −0 actionpack/test/template/tag_helper_test.rb
@@ -25,9 +25,13 @@ module TagHelper
# escaping.
#
# ==== Options
- # The +options+ hash is used with attributes with no value like (<tt>disabled</tt> and
- # <tt>readonly</tt>), which you can give a value of true in the +options+ hash. You can use
- # symbols or strings for the attribute names.
+ # Use +true+ with boolean attributes that can render with no value (like
+ # +disabled+ and +readonly+).
+ #
+ # HTML5 data-* attributes can be set with a single +data+ key and a hash
+ # value of sub-attributes. Sub-attribute keys will be dasherized.
+ #
+ # You can use symbols or strings for the attribute names.
#
# ==== Examples
# tag("br")
@@ -44,6 +48,9 @@ module TagHelper
#
# tag("img", { :src => "open &amp; shut.png" }, false, false)
# # => <img src="open &amp; shut.png" />
+ #
+ # tag("div", { :data => { :name => 'Stephen', :city_state => %w(Chicago IL) } })
+ # # => <div data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" data-name="Stephen" />
def tag(name, options = nil, open = false, escape = true)
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
end
@@ -118,7 +125,13 @@ def tag_options(options, escape = true)
unless options.blank?
attrs = []
options.each_pair do |key, value|
- if BOOLEAN_ATTRIBUTES.include?(key)
+ if key.to_s == 'data' && value.is_a?(Hash)
+ value.each do |k, v|
+ final_v = [String, Symbol].include?(v.class) ? v : v.to_json
+ final_v = html_escape(final_v) if escape
+ attrs << %(data-#{k.to_s.dasherize}="#{final_v}")
+ end
+ elsif BOOLEAN_ATTRIBUTES.include?(key)
attrs << %(#{key}="#{key}") if value
elsif !value.nil?
final_value = value.is_a?(Array) ? value.join(" ") : value
@@ -110,4 +110,11 @@ def test_skip_invalid_escaped_attributes
def test_disable_escaping
assert_equal '<a href="&amp;" />', tag('a', { :href => '&amp;' }, false, false)
end
+
+ def test_data_attributes
+ ['data', :data].each { |data|
+ assert_dom_equal '<a data-a-number="1" data-array="[1,2,3]" data-hash="{&quot;key&quot;:&quot;value&quot;}" data-string="hello" data-symbol="foo" />',
+ tag('a', { data => { :a_number => 1, :string => 'hello', :symbol => :foo, :array => [1, 2, 3], :hash => { :key => 'value'} } })
+ }
+ end
end

0 comments on commit 5e79094

Please sign in to comment.