1

In my ruby on rails app I have to use recursion to render nested comments.

Because of this I decided to offload the rendering into a function in a helper.

The basic structure of the function is like this:

def display_comments(tree)
    to_render = ""
    to_render << render({:partial => 'comment', :locals => {:body => tree[:body]}})
    tree[:children].each do |child|
        to_render << display_comment(child)
    end
    return to_render
end

and in the view I call it like this:

<% if comment_forest.length > 0 %>
    <% comment_forest.each do |tree| %>
        <%= display_comments(tree)
    <% end %>
<% end %>

However, on the webpage, rails escapes all the html and it ends up looking like this:

enter image description here

Razor Storm
  • 12,167
  • 20
  • 88
  • 148

1 Answers1

3

You probably want to call html_safe before you return. The sanitization behavior changed a bit in Rails 3 (XSS protection was enabled by default), so you may also want to check out this SO discussion of raw, h, and html_safe, which links to Yehuda Katz's explanation of SafeBuffers in Rails 3.

Community
  • 1
  • 1
sczizzo
  • 3,196
  • 20
  • 28
  • Cool, that worked! Surprisingly, rails still escaped the html from user inputted information. What is this magic? :O – Razor Storm Dec 27 '11 at 23:57
  • Actually in retrospect, the user inputted data is probably being escaped when it is saved not when it is displayed. Correct? – Razor Storm Dec 27 '11 at 23:57
  • 1
    According to Katz, if you concatenate a safe string with an unsafe one, the unsafe string is first escaped, which is probably what's happening here. – sczizzo Dec 28 '11 at 00:02