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

旧时模样 提交于 2019-12-12 12:10:09

问题


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 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?


回答1:


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



来源:https://stackoverflow.com/questions/5811488/ruby-on-railss-content-for-will-do-an-automatic-html-escape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!