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?
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="["Chicago","IL"]" />
Have you tried using quotes with symbol? Something like:
:"data-foo" => :bar
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)
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With