使用rails content_tag helper使用html5数据属性的最佳方法是什么? [英] Best way to use html5 data attributes with rails content_tag helper?
本文介绍了使用rails content_tag helper使用html5数据属性的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当然,问题是ruby符号不喜欢连字符。所以像这样的东西显然是行不通的:
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
我喜欢后者,但两者看起来有点毛病。有人知道更好的方法吗?
解决方案
Rails 3.1附带内置助手:
http://api.rubyonrails .org / classes / ActionView / Helpers / TagHelper.html#method-i-tag
例如,
tag(div,:data => {:name =>'Stephen',:city_state =>%w(Chicago IL)})
#=> < div data-name =Stephendata-city-state =[& quot; Chicago& quot;," IL& quot;]/>
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"]" />
这篇关于使用rails content_tag helper使用html5数据属性的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文