在视图中使用辅助函数可以转义html? [英] Using helpers in a view escapes the html?
问题描述
在我的ruby on rails应用程序中,我必须使用递归来呈现嵌套的注释.
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.
函数的基本结构如下:
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 %>
但是,在网页上,rails会转义所有html,最终看起来像这样:
However, on the webpage, rails escapes all the html and it ends up looking like this:
推荐答案
您可能要在返回之前致电html_safe
.清理行为在Rails 3中有所更改(默认情况下启用了XSS保护),因此您可能还想查看在Rails 3中解释SafeBuffers .
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.
这篇关于在视图中使用辅助函数可以转义html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!