0

I created a helper in application_helper to show my flash messages. The code is based on code I found on Stack Overflow, with my modifications:

   def show_flash
     flash_names = [:notice, :warning, :message, :error]
     flash_html = ''
     for name in flash_names
       if flash[name]
         flash_html = flash_html + "<div class=\"#{name}\">#{flash[name]}</div>"
       end
       flash[name] = nil;
     end
     flash_html
   end

When I run this, instead of getting the flash message on my page, I get the actual html that my show_flash helper generated, including all the markup:

      <div class="notice">Item was successfully updated.</div>

My application.html.erb file looks like this:

 <!DOCTYPE html>
 <html>
 <head>
   <title>My Application</title>
   <%= stylesheet_link_tag    "application" %>
   <%= javascript_include_tag "application" %>
   <%= csrf_meta_tags %>
 </head>
 <body>
<h1 align="center">Welcome to XYZ Application</c></h1>
<%= show_flash %>

 <%= yield %>

 </body>
 </html>

What am I doing wrong?

Veger
  • 37,240
  • 11
  • 105
  • 116

1 Answers1

1

You need to make add .html_safe to make it treat as an HTML element

def show_flash
   flash_names = [:notice, :warning, :message, :error]
   flash_html = ''
   for name in flash_names
     if flash[name]
       flash_html = flash_html + "<div class=\"#{name}\">#{flash[name]}</div>"
     end
     flash[name] = nil;
   end
   flash_html.html_safe # added this to make it appear as an HTML element instead of as real string
 end

You can see the different options in this question, raw vs. html_safe vs. h to unescape html. The code, you referred to might have been written in Rails 2. In Rails 3, any string that is outputted in the html page is HTML escaped by default. In Rails 2, we needed to use h helper for escaping HTML, but in Rails 3, it is escaped by default. So, if you really need to show unescaped HTML, you need to make use of either raw or .html_safe. raw can be called only from the views and controllers, so in the helpers, you might use html_safe.

Community
  • 1
  • 1
rubyprince
  • 17,559
  • 11
  • 64
  • 104
  • Perfect, that fixed it! Thank you for your help, and for such a quick response – user1904869 Dec 14 '12 at 19:09
  • @user1904869..you can accept the answer by clicking on the tick mark on the left side of my answer ([image](http://cdn.sstatic.net/img/faq/faq-accept-answer.png)) – rubyprince Dec 14 '12 at 19:20