Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to use html5 data attributes with rails content_tag helper?

The issue, of course, is that ruby symbols don't like hyphens. So something like this obviously won't work:

content_tag(:div, "Some Text", :id => "foo", :data-data_attr => some_variable)

One option is to use a string rather than a symbol:

content_tag(:div, "Some Text", :id => "foo", 'data-data_attr' => some_variable)

Or I could just interpolate:

"<div id='foo' data-data_attr='#{some_variable}'>Some Text</div>".html_safe

I sorta prefer the later but both seem a little gross. Anyone know of a better way?

like image 706
Cory Schires Avatar asked Nov 23 '10 16:11

Cory Schires


4 Answers

Rails 3.1 ships with built-in helpers:

http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-tag

E.g.,

tag("div", :data => {:name => 'Stephen', :city_state => %w(Chicago IL)})
# => <div data-name="Stephen" data-city-state="[&quot;Chicago&quot;,&quot;IL&quot;]" />
like image 195
stephencelis Avatar answered Oct 14 '22 16:10

stephencelis


Have you tried using quotes with symbol? Something like:

:"data-foo" => :bar
like image 34
Eimantas Avatar answered Oct 14 '22 16:10

Eimantas


A helper's not a bad idea but seems a bit of an overkill for what's essentially me being fusy about syntax. I suppose there's nothing built into rails which is what I was hoping for. I'll just use this:

content_tag(:div, "Some Text", :id => "foo", 'data-data_attr' => some_variable)
like image 11
Cory Schires Avatar answered Oct 14 '22 15:10

Cory Schires


Building on previous answers, here's the canonical way to do it now:

content_tag(:div, "Some Text", id: "foo", data: { attr: some_variable })
content_tag(:div, "Some Text", id: "foo", data: { "other-attr" => some_variable })

Which generates:

<div id="foo" data-attr="some variable">Some Text</div>
<div id="foo" data-other-attr="some variable">Some Text</div>
like image 9
coisnepe Avatar answered Oct 14 '22 15:10

coisnepe