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:
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 ofraw
,h
, andhtml_safe
, which links to Yehuda Katz's explanation of SafeBuffers in Rails 3.