在 Rails content_tag helper 中使用 html5数据属性的最佳方法是什么?

当然,问题在于红宝石符号不喜欢连字符,所以像这样的东西显然是行不通的:

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

一种选择是使用字符串而不是符号:

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

或者我可以直接插入:

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

我比较喜欢后者,但两者都有点恶心,有人知道更好的方法吗?

65495 次浏览

Have you tried using quotes with symbol? Something like:

:"data-foo" => :bar

You can always create you own helper function so then you can write

<%= div_data_tag the_id, some_text, some_data %>

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)

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;]" />

JQuery Air (codeschool.com) Level 1, Example 1

Codeschool/platform-independent version

<section id="tabs">
<ul>
<li><a href="#2012-09-27" data-flights="6">Sep 27</a></li>
<li><a href="#2012-09-28" data-flights="5">Sep 28</a></li>
<li><a href="#2012-09-29" data-flights="5">Sep 29</a></li>
</ul>
</section>

Rails Version

<section id="tabs">
<ul>
<li><%= content_tag(:a, "Sep 27",:href=> "#2012-09-27", :data => { :flights => "6" } ) %></li>
<li><%= content_tag(:a, "Sep 28",:href=> "#2012-09-28", :data => { :flights => "5" } ) %></li>
<li><%= content_tag(:a, "Sep 29",:href=> "#2012-09-29", :data => { :flights => "5" } ) %></li>
</ul>
</section>

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>