rails 3 + prawn pdf + html_safe



我正在使用对虾宝石生成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标签的内容,甚至我也尝试过应用htmlsafe,但它并没有转义标签。

是否可以在对虾pdftable中使用/应用htmlsafe来转义html标签?

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

听起来,您想要做的不是转义HTML,而是从字符串中剥离HTML标记。Rails在ActionView::Helpers::SanitizeHelper中有一个HTML清理程序,但默认情况下它允许某些标记;可以使用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方法。

注意,&nbsp;仍然在字符串中;如果要删除这些HTML实体,则需要使用其他方法;HTMLEntities宝石就是这样一种方法:

[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;)。

如果你正在寻找一种使用对虾内联格式的方法,你也可以这样做:

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

最新更新