在 Rails ERB 视图中,如何防止下划线被转换为连字符?
In Rails ERB view, how can I prevent underscore from being converted to hyphen?
在 ERB 视图中有以下代码:
<%= content_tag(:div, id: 'stat', data: {_var_: '_foo_'}) %>
生成以下 HTML:
<div id="stat" data--var-="_foo_">
</div>
我的目的是获得
<div id="stat" data-_var_="_foo_">
</div>
即我不要
data--var-
而是
data-_var_
请问我怎样才能做到这一点?
正如 ActionView::Helpers::TagHelper docs:
中所指出的
To play nicely with JavaScript conventions sub-attributes are
dasherized. For example, a key user_id would render as data-user-id
and thus accessed as 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
如果您不想将您的密钥打乱,一个可能的"解决方法"就是直接在options hash中设置data-attribute
,像这样:
<%= content_tag(:div, "test", { id: 'stat', 'data-_var_': '_foo_' }) %>
这样,Rails 将呈现:
<div id="stat" data-_var_="_foo_">test</div>
在 ERB 视图中有以下代码:
<%= content_tag(:div, id: 'stat', data: {_var_: '_foo_'}) %>
生成以下 HTML:
<div id="stat" data--var-="_foo_">
</div>
我的目的是获得
<div id="stat" data-_var_="_foo_">
</div>
即我不要
data--var-
而是
data-_var_
请问我怎样才能做到这一点?
正如 ActionView::Helpers::TagHelper docs:
中所指出的To play nicely with JavaScript conventions sub-attributes are dasherized. For example, a key user_id would render as data-user-id and thus accessed as 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
如果您不想将您的密钥打乱,一个可能的"解决方法"就是直接在options hash中设置data-attribute
,像这样:
<%= content_tag(:div, "test", { id: 'stat', 'data-_var_': '_foo_' }) %>
这样,Rails 将呈现:
<div id="stat" data-_var_="_foo_">test</div>