开发者

Ruby on Rails's content_for will do an automatic HTML escape?

开发者 https://www.devze.com 2023-02-28 23:44 出处:网络
Using Rails 3.0.6, I found that in the view, if I do a content_for :food_name, \"Macaroni & Cheese\"

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 &amp; automatically. Now, because there are places where I actually do a #{h content_for(:food_name)} and it will be escaped twice (to become &amp;amp;), or because I have values in <meta> description, it will be strang开发者_运维百科e 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?


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 inraw at those places.

For more information, refer to this really great article by Yehuda katz.
safebuffers-and-rails-3-0

0

精彩评论

暂无评论...
验证码 换一张
取 消