Ruby on Rails 的 content_for 会自动进行 HTML 转义吗?
使用 Rails 3.0.6,我发现在视图中,如果我执行
content_for :food_name, "Macaroni & Cheese"
then 当我使用 content_for(:food_name)
取回它时,那么 &
将是已经制作成 &
了。 如果我执行 content_for(:food_name).html_safe
也没关系,&
仍然已制成 &
。
但如果按照以下方式完成,则不会转义:
content_for :food_name, "Macaroni & Cheese".html_safe
在这种情况下,&
不会自动更改为&
。现在,因为有些地方 我实际上做了一个 #{h content_for(:food_name)}
,它将被转义两次(变成 &
),或者 因为我在描述中有值,所以对某些值调用
h
而不调用它会很奇怪 关于其他一些值。
另外,一个大问题是,如果它自动转义,如果我添加 " - come see us!"
到它的末尾,并依靠 Rails 3 来转义它,现在会怎么样?然后,&
被转义两次。
在 content_for
文档中:
http ://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for
我没有看到任何类似的描述。那么上面的描述是否正确 或者文档更正确——事实上没有自动 HTML 转义?
从上面网页的源代码来看,content_for
调用了capture
,并且它执行了ERB::Util.html_escape
, 所以实际上存在自动转义,但真的应该存在吗?为什么?是否也没有记录 capture
执行 自动逃脱?
Using Rails 3.0.6, I found that in the view, if I do a
content_for :food_name, "Macaroni & Cheese"
Then when I get it back using content_for(:food_name)
, then the &
will be made into &
already.
It doesn't matter if I do a content_for(:food_name).html_safe
, the &
is still made into &
already.
But if done the following way, then it is not escaped:
content_for :food_name, "Macaroni & Cheese".html_safe
In this case, the &
will not change to &
automatically. Now, because there are places where
I actually do a #{h content_for(:food_name)}
and it will be escaped twice (to become &
), or
because I have values in <meta>
description, it will be strange to call h
on some values and not call it
on some other values.
Also, one big catch is, if it escapes automatically, and what if I add " - come see us!"
to the end of it, and rely on Rails 3 to escape it, now then, the &
is escaped twice.
In the content_for
docs:
http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for
I don't see any description like that. So is the description above correct
or is the docs more correct -- that in fact there is no automatic HTML escape?
It seems like from the source code on the above webpage, content_for
calls capture
, and it does an ERB::Util.html_escape
,
so there is in fact an automatic escape, but should there really be, and why? Is it also not documented that capture
does an
automatic escape?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您不希望 Rails 转义这些字符时,请使用
<%= raw some_stuff %>
,否则使用简单调用。您始终知道内容可能在哪些区域,如果转义则可能会被修改,因此您可以简单地将
raw
放入这些位置。有关更多信息,请参阅 Yehuda katz 撰写的这篇非常精彩的文章。
safebuffers-and-rails-3-0
Use
<%= raw some_stuff %>
when you don't want Rails to escape these characters, otherwise use the simple call.You always know the areas where the content can be such, that could be modified if escaped, so you can simply fit in
raw
at those places.For more information, refer to this really great article by Yehuda katz.
safebuffers-and-rails-3-0