Ruby on Rails 的 content_for 会自动进行 HTML 转义吗? [英] Ruby on Rails's content_for will do an automatic HTML escape?

查看:38
本文介绍了Ruby on Rails 的 content_for 会自动进行 HTML 转义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Rails 3.0.6,我发现在视图中,如果我做一个

Using Rails 3.0.6, I found that in the view, if I do a

content_for :food_name, "Macaroni & Cheese"

然后当我使用 content_for(:food_name) 取回它时,那么 & 将变成 &.如果我做一个 content_for(:food_name).html_safe 没关系,& 仍然已经变成了 &.

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

在这种情况下,& 不会自动变为 &.现在,因为有些地方我实际上做了一个 #{h content_for(:food_name)} 并且它会被转义两次(变成 &amp;amp;),或者因为我在 <meta> 描述中有值,所以在某些值上调用 h 而不是调用它会很奇怪其他一些价值观.

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.

另外,一个重要的问题是,如果它自动转义,如果我添加 " - come see us!" 到它的末尾,并依靠 Rails 3 转义现在,& 被转义了两次.

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.

content_for 文档中:

http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

我没有看到任何类似的描述.那么上面的描述是否正确还是文档更正确——实际上没有自动 HTML 转义?

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?

从上面网页的源代码来看,content_for 调用了 capture,它做了一个 ERB::Util.html_escape,所以实际上有一个自动逃逸,但真的应该有,为什么?是否也没有记录 capture 执行自动逃生?

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?

推荐答案

当你不希望 Rails 对这些字符进行转义时使用 <%= raw some_stuff %>,否则使用简单的称呼.

Use <%= raw some_stuff %> when you don't want Rails to escape these characters, otherwise use the simple call.

您总是知道内容可能存在的区域,如果转义就可以修改这些区域,因此您可以简单地将raw 放入这些地方.

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.

有关更多信息,请参阅 Yehuda katz 撰写的这篇非常棒的文章.
safebuffers-and-rails-3-0

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

这篇关于Ruby on Rails 的 content_for 会自动进行 HTML 转义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆