Question

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.

Was it helpful?

Solution 2

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:

def show_flash
  a=content_tag(:span, "",:escape=>false)
  [:success, :info, :error, :warning].each do |key|
    a = a+content_tag(:div, flash[key], :id => key, :class => "#{key}", :escape=>false) unless flash[key].blank?
  end     
  a
end

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.

OTHER TIPS

Because "" wasn't marked as html_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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top