Rails:视图:content_tag 帮助程序
我有一个控制器,它在渲染视图并输出错误之前执行以下操作。
flash[:error]="Flash error"
flash[:info] = "Flash info"
我想很好地格式化它。为此,我编写了一个如下所示的帮助程序
def show_flash
a=""
[:success, :info, :error, :warning].each do |key|
a += content_tag(:div, flash[key], :id => key, :class => "#{key}") unless flash[key].blank?
end
end
在我看来,我调用:
<%= show_flash %>
当我尝试运行此程序时,网页会呈现 show_flash 的全文,包括 div 标签、尖括号等。当我检查该元素(使用 Firefox 或 Chrome)时,它显示用双引号括起来的文本。
然后我尝试更改助手中的一行,如下所示:
a = content_tag(:div, flash[key], :id=>key, :class=>"#{key]") unless flash[key].blank?
即我只会捕获最后一个内容标签(错误)而不是两者。
在第二种情况下,Web 浏览器使用我的 CSS 规则为“error”类呈现正确格式化的 div 标签。我没有看到浏览器中打印出任何 div 标签。
为什么连接两个 content_tag 元素会让我如此悲伤?
我很感激你能给我的任何帮助。
I have a controller which does the following line before rendering the view and outputting an error.
flash[:error]="Flash error"
flash[:info] = "Flash info"
I would like to format this nicely. For that I wrote a helper which looks like this
def show_flash
a=""
[:success, :info, :error, :warning].each do |key|
a += content_tag(:div, flash[key], :id => key, :class => "#{key}") unless flash[key].blank?
end
end
In my view, I call:
<%= show_flash %>
When I try to run this, the web page renders the full text of show_flash, including the div tags, angle brackets and all. When I inspect the element (using Firefox or Chrome), it shows the text surrounded with double quotes.
Then I tried changing one line in the helper as follows:
a = content_tag(:div, flash[key], :id=>key, :class=>"#{key]") unless flash[key].blank?
i.e. I would only capture the last content tag (error) instead of both of them.
In the second case, the web browser rendered the div tag formatted properly with my CSS rules for the "error" class. I didn't see any div tags printed out in the browser.
Why did concatenating two content_tag elements cause me this grief?
I appreciate any help you can give me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
""
未标记为html_safe
。这是 Rails 3 中默认启用的 Rails XSS 保护的一部分。您可能会发现此 Railscast 有关 XSS 保护的信息。
Because
""
wasn't marked ashtml_safe
. This is part of Rails' XSS protection that is enabled by default in Rails 3.You may find this Railscast on XSS protection informative.
事实证明,从 Rails 2 到 Rails 3 时,默认情况下会启用 html 转义,并且您必须在连接
content_tag
字符串之前显式禁用它。代码如下所示:该选项
:escape=>false
是使其工作所需的内容。Andrew Marshall 为我指明了正确的方向,经过一番搜索,我偶然发现了 耶胡达的智慧之言。这就是
:escape
子句变得明显的地方。It turns out that when going from Rails 2 to Rails 3, html escaping is enabled by default, and you must explicitly disable it before concatenating
content_tag
strings. The code looks like:That option,
:escape=>false
is what it took to make it work.Andrew Marshall pointed me in the right direction, and after some searching, I stumbled on the words of wisdom from Yehuda. That's where the
:escape
clause became obvious.