diff options
Diffstat (limited to 'actionpack')
-rw-r--r-- | actionpack/lib/action_view/helpers/tag_helper.rb | 21 | ||||
-rw-r--r-- | actionpack/test/template/tag_helper_test.rb | 7 |
2 files changed, 24 insertions, 4 deletions
diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index 1b9e152b4d..b00b7636c3 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -25,9 +25,13 @@ module ActionView # 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 ActionView # # tag("img", { :src => "open & shut.png" }, false, false) # # => <img src="open & shut.png" /> + # + # tag("div", { :data => { :name => 'Stephen', :city_state => %w(Chicago IL) } }) + # # => <div data-city-state="["Chicago","IL"]" 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 @@ module ActionView 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 diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb index c742683821..60b466a9ff 100644 --- a/actionpack/test/template/tag_helper_test.rb +++ b/actionpack/test/template/tag_helper_test.rb @@ -110,4 +110,11 @@ class TagHelperTest < ActionView::TestCase def test_disable_escaping assert_equal '<a href="&" />', tag('a', { :href => '&' }, 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="{"key":"value"}" 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 |