ruby-on-rails - rails 3 + prawn pdf + html_safe

标签 ruby-on-rails

我正在使用 prawn gem 生成 PDF 报告,

@user.description returns as string "<b>sample text</b> &nspb; <p>sample text</p>"

将值附加到 pdf 表时
pdftable = Prawn::Document.new
pdftable.table([["#{@user.description}"]],
         :column_widths => {0 => 50, 1 => 60, 2 => 280, }, :row_colors => ["ffffff"])

在这种情况下,生成的 pdf 包含带有 html 标签的内容,即使我尝试应用 html_safe 但它没有转义标签。

是否可以在 prawn pdftable 中使用/应用 html_safe 以逃避 html 标签?

最佳答案

再次,html_safe不是你应该使用的方法;它不会做你认为它会做的事情。全部 html_safe do 是将字符串标记为安全的,从而告诉 Rails 不需要在 View 中对其进行转义。使用 Prawn 时,它没有任何效果。

听起来您想要做的不是转义 HTML,而是从字符串中去除 HTML 标签。 Rails 在 ActionView::Helpers::SanitizeHelper 中有一个 HTML sanitizer ,但默认情况下它允许某些标签;您可以使用 tags 关闭此行为属性。

class MyClass
  include ActionView::Helpers::SanitizeHelper

  def remove_html(string)
    sanitize(string, :tags => {}) # empty tags hash tells it to allow no tags
  end
end

obj = MyClass.new
obj.remove_html "<b>sample text</b> &nspb; <p>sample text</p>"
 => "sample text &nspb; sample text"

您可以 include ActionView::Helpers::SanitizeHelper在您的 Controller 中访问 sanitize方法。

请注意 &nbsp;仍在字符串中;如果要删除这些 HTML 实体,则需要使用其他方法; HTMLEntities gem是这样一种方法:
[1] pry(main)> require 'htmlentities'
=> true
[2] pry(main)> coder = HTMLEntities.new
=> #<HTMLEntities:0x007fb1c126a910 @flavor="xhtml1">
[3] pry(main)> string = "sample text &nbsp; sample text"
=> "sample text &nbsp; sample text"
[4] pry(main)> coder.decode string
=> "sample text   sample text"

(请注意,在您的示例中,文本显示 &nspb; 而不是 &nbsp; )。

关于ruby-on-rails - rails 3 + prawn pdf + html_safe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8722925/

相关文章:

ruby-on-rails - 重新加载在Rspec中不起作用的对象

ruby-on-rails - 从移动设备测试应用程序时出错 - ERR_CONNECTION_REFUSED

ruby-on-rails - Rails 4 ActionMailer 不在开发模式下发送电子邮件

ruby-on-rails - 加速 rspec Controller 测试 : using before all fails?

html - Bootstrap 3 的事件按钮

css - 使用 btn-block 使 Bootstrap-Select 按钮全宽(响应)

ruby-on-rails - 如何读取上传的文件

ruby-on-rails - 在 Rails 中转义 HTML 字符的同时安全地链接用户生成的内容

ruby-on-rails - 如何从克隆的 ActiveRecord 模型中删除只读状态?

jquery - 让 Jquery 和 Bootstrap 与 Rails 6 配合使用