我正在使用 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
方法。请注意
仍在字符串中;如果要删除这些 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 sample text"
=> "sample text sample text"
[4] pry(main)> coder.decode string
=> "sample text sample text"
(请注意,在您的示例中,文本显示
&nspb;
而不是
)。
关于ruby-on-rails - rails 3 + prawn pdf + html_safe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8722925/