开发者

Rails 3 is messing with my flash!

开发者 https://www.devze.com 2023-01-18 14:34 出处:网络
I have a flash_helper that I inconveniently downloaded from some web tutorial, which is now coming back to whack me on the head. On the good side, I\'m sure the many talented coders here will find thi

I have a flash_helper that I inconveniently downloaded from some web tutorial, which is now coming back to whack me on the head. On the good side, I'm sure the many talented coders here will find this easy. :)

# application_helper
def flash_helper
[:notice, :warning, :message].map { |f| content_tag(:div, flash[f], :class => f) if flash[f] }
end

This code, combined with <%= flash_helper %> in my views, is leading to the following html code generated:

[&quot;&lt;div class=\&quot;notice\&quot;&gt;Your account has been reactivated.&lt;/div&gt;&quot;, ni开发者_如何学Pythonl, nil]

...which renders as this rather unattractive string in the view itself:

["<div class=\"notice\">Your account has been reactivated.</div>", nil, nil]

How do I rewrite the code to sort this out?


[nil, nil, nil]

The above string is being sent to all of my views by the flash_helper code above when there is no flash. How can that code be rewritten to output nothing when there is no flash?


You need launch html_safe on all your String, on an array.

# application_helper
def flash_helper
  [:notice, :warning, :message].map { |f| 
    content_tag(:div, flash[f].html_safe, :class => f) if flash[f] 
  }.compact
end


By default Rails 3 escapes HTML unless told otherwise. All you need to do is call .html_safe on the string being generated. Here is an overview:

HTML SAFE

0

精彩评论

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

关注公众号