正如::的ActionView指出助手:: TagHelperdocs:
使用JavaScript公約發揮很好子屬性是 底線轉換。例如,密鑰user_id將呈現爲數據用戶ID 並因此作爲dataset.userId被訪問。
爲了說明這一點,你可以在Rails的源代碼(tag_helper.rb)prefix_tag_option
檢查調用key.to_s.dasherize
:
def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
#...#
content_tag_string(name, content_or_options_with_block, options, escape)
#...#
end
def content_tag_string(name, content, options, escape = true)
tag_options = tag_options(options, escape) if options
#...#
end
def tag_options(options, escape = true)
# ...
# TAG_PREFIXES = ['aria', 'data', :aria, :data].to_set
# invoke prefix_tag_option only if it's a data- sub-attributes
if TAG_PREFIXES.include?(key) && value.is_a?(Hash)
#...#
output << prefix_tag_option(key, k, v, escape)
end
#...#
end
def prefix_tag_option(prefix, key, value, escape)
key = "#{prefix}-#{key.to_s.dasherize}"
#...#
end
如果你不想dasherize你的鑰匙,可能「 解決方法「是直接在選項散列中設置data-attribute
,如下所示:
<%= content_tag(:div, "test", { id: 'stat', 'data-_var_': '_foo_' }) %>
這樣,Rails會呈現:
<div id="stat" data-_var_="_foo_">test</div>
榮譽給@mrlew了非常詳細的和說教的答案。謝謝 ! –
@AlbertAnstett不客氣:) – mrlew