Using helpers in a view escapes the html?

2019-07-27 04:15发布

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

1条回答
▲ chillily
2楼-- · 2019-07-27 04:28

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.

查看更多
登录 后发表回答