【问题标题】:Using helpers in a view escapes the html?在视图中使用帮助器会转义 html?
【发布时间】:2012-01-28 20:16:24
【问题描述】:

在我的 ruby​​ on rails 应用程序中,我必须使用递归来渲染嵌套的 cmets。

因此,我决定将渲染卸载到帮助程序中的函数中。

函数的基本结构是这样的:

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 %>

但是,在网页上,rails 转义了所有 html,最终看起来像这样:

【问题讨论】:

    标签: ruby-on-rails model-view-controller view helper


    【解决方案1】:

    您可能想在返回之前致电html_safe。 Rails 3 中的清理行为发生了一些变化(默认情况下启用了 XSS 保护),因此您可能还想查看 this SO discussion of raw, h, and html_safe,它链接到 Yehuda Katz 的 explanation of SafeBuffers in Rails 3

    【讨论】:

    • 酷,成功了!令人惊讶的是,rails 仍然从用户输入的信息中转义了 html。这是什么魔法? :O
    • 其实回想起来,用户输入的数据很可能是在保存时被转义,而不是在显示时。对吗?
    • 根据 Katz 的说法,如果你将一个安全字符串与一个不安全字符串连接起来,那么不安全字符串首先会被转义,这可能就是这里发生的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2013-04-17
    • 2017-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多