Rails view helpers get raw in 3

Having trouble outputting HTML from you views helper method? Rails 3 provides XSS protection by default. This new feature may slightly change the way you render HTML in your views.

In rails we all use helper methods to output HTML. For example, here is my view where I place some html to display within a table column.

1
2
3
4
5
    <tr align="top">
      <% @week_shifts.each do |k,v|%>
        <td><%= shift_cell_layout(v) %> </td>
      <% end %>
    </tr>

and the corresponding helper method might look like this

1
2
3
4
5
module ScheduleHelper
  def shift_cell_layout(shift)
    "<strong>#{shift.user.name}</strong> <br /> #{shift.hours_string}"
  end
end

Rails 3 introduced XSS protection by default, eliminating the need for the developer to escape strings with the h helper. This means the html you intended to output above will be escaped, looking something like this.

1
2
3
&lt;strong&gt;tim&lt;/strong&gt;
&lt;br /&gt;7:00AM - 4:00PM
&nbsp;

Probably not the pretty web 2.0 experience you were intending :) Mark the string as “raw” and Rails 3 will output it as entered.

1
2
3
4
5
module ScheduleHelper
  def shift_cell_layout(shift)
    raw "<strong>#{shift.user.name}</strong> <br /> #{shift.hours_string}"
  end
end

You can also achieve the same using the html_safe method.

Yehuda Katz explains in more detail in his safebuffers and rails 3 post

Tags: , , , , , , ,

Leave a comment

Powered by WP Hashcash