2011-12-27 35 views
1

在我的ruby on rails应用程序中,我必须使用递归来呈现嵌套注释。在视图中使用助手转义的HTML?

因为这个原因,我决定将辅助功能中的渲染转换为函数。

功能的基本结构是这样的:

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 

,并在视图中我这样称呼它:

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

然而,在网页上,轨道逃脱所有的HTML和它结束了看起来像这样:

enter image description here

回答

3

ÿ ou可能要在返回之前致电html_safe。 Rails 3中的消毒行为有所变化(默认情况下启用了XSS保护),因此您可能还想查看链接到Yehuda Katz的explanation of SafeBuffers in Rails 3this SO discussion of raw, h, and html_safe

+0

很酷,工作!令人惊讶的是,Rails仍然逃离了用户输入信息中的html。这是什么魔术? :O – 2011-12-27 23:57:17

+0

实际上回想起来,用户输入的数据在保存时可能会被转义,而不是显示时。正确? – 2011-12-27 23:57:37

+1

根据Katz的说法,如果将不安全的字符串与不安全的字符串连接在一起,那么不安全的字符串首先会被转义,这可能是这里发生的事情。 – sczizzo 2011-12-28 00:02:44