Ruby on rails 轨道3和x2B;对虾pdf+;html_安全

Ruby on rails 轨道3和x2B;对虾pdf+;html_安全,ruby-on-rails,Ruby On Rails,我正在使用prawn gem生成PDF报告 @user.description returns as string "<b>sample text</b> &nspb; <p>sample text</p>" 在本例中,生成的pdf包含带有html标记的内容,即使我尝试应用html_safe,但它并不是转义标记 是否可以在prawn pdftable中使用/应用html\u-safe,以逃避html标记?再次强调,html\u-safe不

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

@user.description returns as string "<b>sample text</b> &nspb; <p>sample text</p>"
在本例中,生成的pdf包含带有html标记的内容,即使我尝试应用html_safe,但它并不是转义标记


是否可以在prawn pdftable中使用/应用html\u-safe,以逃避html标记?

再次强调,
html\u-safe
不是您应该使用的方法;它不会做你认为它会做的事。html\u safe所做的一切就是将字符串标记为safe,从而告诉Rails它不需要在视图中转义它。使用对虾时,它不会有任何效果

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

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"

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

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

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

PDF中显示的是什么?您希望显示什么?在PDF中,它显示的是“示例文本&nspb;示例文本”

,而应该是唯一的文本,即“示例文本示例文本”,html_safe应该是appliedSorry,但这不是
html\u safe
所做的——它只是告诉Rails在视图中使用字符串时不应转义。查看解决方案。如何使htMl_在controller中安全工作,或者是否有其他方法。您是否尝试了所有相同的方法,但没有引号<代码>pdftable.table([[@user.description.html\u-safe]]…非常感谢,它对我帮助不大,但仍然有一些由HTML编辑器Tinymce生成的标记没有被转换为带有HTML属性的实际文本。但是当我在视图中使用raw或htnm\u safe时,它工作得非常好。我使用了这个答案,但我在视图中渲染,因此不得不使用
pdf.make\u cell(…)
[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"
pdftable = Prawn::Document.new
cell = make_cell(content: "#{@user.description}", inline_format: true)
pdftable.table([[cell]])