Reputation: 1
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?
Upvotes: 0
Views: 104
Reputation: 17793
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
.
Upvotes: 1