不要在轨道上的ruby中转义html

ale*_*rke 50 ruby-on-rails ruby-on-rails-3

rails 3似乎逃脱了一切,包括html.我尝试过使用raw()但它仍然逃脱了html.有解决方法吗?这是我正在使用的帮手(/helpers/application_helper.rb):

module ApplicationHelper
  def good_time(status = true)
    res = ""
    if status == true
      res << "Status is true, with a long message attached..."
    else
      res << "Status is false, with another long message"
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我使用以下代码在视图中调用帮助器:

<%= raw(good_time(true)) %>
Run Code Online (Sandbox Code Playgroud)

Mis*_*cha 88

你可以.html_safe像这样使用:

def good_time(status = true)
  if status
    "Status is true, with a long message attached...".html_safe
  else
    "Status is false, with another long message".html_safe
  end
end

<%= good_time(true) %>
Run Code Online (Sandbox Code Playgroud)

  • 出色的答案.尽管有15分钟的教程,但总是让我感到惊讶的是Rails中一些最琐碎的任务有多难.推土机一切都很好,但有时你需要的是一个虾叉.:) (11认同)

Dre*_*awn 5

我遇到了同样的事情,并发现了比使用更安全的解决方案html_safe,尤其是在您引入动态字符串之后。

首先,更新后的代码:

def good_time(long_message1, long_message2, status = true)
  html = "".html_safe
  html << "Status is #{status}, "
  if status
    html << long_message1
  else
    html << long_message2
  end
  html
end

<%= good_time(true) %>
Run Code Online (Sandbox Code Playgroud)

long_message如果内容不安全,则它会转义内容,但如果它是安全的,则不会对其进行转义。

这允许"long message for success & such."正确显示,但也可以转义"malicious message <script>alert('foo')</script>"

解释归结为——'foo'.html_safe返回一个 ActiveSupport::SafeBuffer,它在任何方面都像一个字符串,除了一个:当你将一个字符串附加到一个 SafeBuffer 时(通过调用 + 或 <<),另一个字符串之前是 HTML 转义的它被附加到 SafeBuffer。当您将另一个 SafeBuffer 附加到 SafeBuffer 时,不会发生转义。Rails 正在使用 SafeBuffers 在幕后渲染所有视图,因此上面更新的方法最终为 Rails 提供了一个 SafeBuffer,我们已经控制它在long_message“按需”而不是“总是”上执行转义。

现在,这个答案的功劳完全归功于 Henning Koch,并且在你所知道的关于 html_safe 的一切都是错误的方面进行了更详细的解释——我上面的回顾只是试图在此链接消失的情况下提供解释的精髓.