簡體   English   中英

從 Rails 上的字符串 Ruby 中剝離 html

[英]Strip html from string Ruby on Rails

我在 Rails 上使用 Ruby,有沒有辦法使用 sanitize 或 equal 方法從字符串中html並僅保留輸入標簽上值屬性內的文本?

如果我們想在模型中使用它

ActionView::Base.full_sanitizer.sanitize(html_string)

這是“strip_tags”方法中的代碼

ActionView::Helpers::SanitizeHelper有一個strip_tags方法:

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html#method-i-strip_tags

編輯:為了獲取 value 屬性中的文本,您可以使用類似 Nokogiri 和 Xpath 表達式的東西將其從字符串中取出。

是的,調用這個: sanitize(html_string, tags:[])

ActionView::Base.full_sanitizer.sanitize(html_string)

標簽和屬性的白名單可以指定如下

ActionView::Base.full_sanitizer.sanitize(html_string, :tags => %w(img br p), :attributes => %w(src style))

以上語句允許標簽imgbrp以及屬性srcstyle

我使用了 Loofah 庫,因為它適用於 HTML 和 XML(文檔和字符串片段)。 它是 html sanitizer gem 背后的引擎。 我只是粘貼代碼示例來展示它的使用有多簡單。

絲瓜寶

unsafe_html = "ohai! <div>div is safe</div> <script>but script is not</script>"

doc = Loofah.fragment(unsafe_html).scrub!(:strip)
doc.to_s    # => "ohai! <div>div is safe</div> "
doc.text    # => "ohai! div is safe "

這個怎么樣?

white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
WHITELIST = ['p','b','h1','h2','h3','h4','h5','h6','li','ul','ol','small','i','u']


[Your, Models, Here].each do |klass| 
  klass.all.each do |ob| 
    klass.attribute_names.each do |attrs|
      if ob.send(attrs).is_a? String
        ob.send("#{attrs}=", white_list_sanitizer.sanitize(ob.send(attrs), tags: WHITELIST, attributes: %w(id style)).gsub(/<p>\s*<\/p>\r\n/im, ''))
        ob.save
      end
    end
  end
end

這在 Rails 6.1.3 中對我有用:

.errors-description
  = sanitize(message, tags: %w[div span strong], attributes: %w[class])

如果要刪除所有 html 標簽,您可以使用

   htm.gsub(/<[^>]*>/,'')

你可以做.to_plain_text:

@my_string = <p>My HTML String</p>
@my_string.to_plain_text
=> My HTML String

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM