【问题标题】:rails 3 + prawn pdf + html_saferails 3 + 虾 pdf + html_safe
【发布时间】:2012-01-04 06:31:08
【问题描述】:

我正在使用 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 标签?

【问题讨论】:

  • PDF 中究竟显示了什么,您想要显示什么?
  • 在 pdf 中显示 "sample text &nspb;

    sample text

    " ,而应该只是文本,即“Sample text sample text”,应该应用 html_safe
  • 抱歉,html_safe 不是这样做的——它只是告诉 Rails 在视图中使用时不应转义字符串。查看this question 以获得解决方案。
  • 如何使 htMl_safe 在控制器中工作,或者是否有任何替代方法。
  • 您是否尝试过都一样,但没有引号? pdftable.table([[@user.description.html_safe]] ...

标签: ruby-on-rails


【解决方案1】:

再一次,html_safe 不是您应该使用的方法;它没有做你认为它做的事情。 html_safe 所做的只是将字符串标记为安全,从而告诉 Rails 它不需要在视图中转义它。使用 Prawn 时没有任何效果。

听起来你想要做的不是escape HTML,而是strip字符串中的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 访问sanitize 方法。

注意&amp;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"

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

【讨论】:

  • 非常感谢,它在一定程度上帮助了我,但仍然有一些从 HTML 编辑器 Tinymce 生成的标签没有被转换为带有 h​​tmlentities 的实际文本。但是当我在视图中使用 raw 或 htnm_safe 时,它​​的效果非常好。
【解决方案2】:

如果您正在寻找一种使用 prawn 内联格式的方法,您还可以执行以下操作:

pdftable = Prawn::Document.new
cell = make_cell(content: "#{@user.description}", inline_format: true)
pdftable.table([[cell]])

【讨论】:

  • 我使用了这个答案,但我在视图中渲染,因此必须使用pdf.make_cell(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 2012-03-23
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 2011-05-22
相关资源
最近更新 更多