首页 > 解决方案 > 如何从 Rails html 中去除标签和样式规则

问题描述

我想使用 sanitize 去除样式标签和嵌入​​的 css 规则。如下所示:

ActionController::Base.helpers.sanitize("<style> .emphasized { font-weight: bold } </style> hey <div class='emphasized'>watch out</div>",  tags: %w(strong b br p ul li em u))
=> " .emphasized { font-weight: bold }  hey watch out"

但仍然给我CSS规则。我是否必须使用 Nokogiri 或其他东西,或者可以消毒处理这个?

标签: ruby-on-rails

解决方案


也许您可以尝试定义一个自定义洗涤器。例如

class MyScrubber < Rails::Html::PermitScrubber
  def initialize
    super
    self.tags = %w(strong b br p ul li em u)
  end

  def scrub(node)
    node.name == 'style' ? node.remove : super(node)
  end
end

ActionController::Base.helpers.sanitize("<style> .emphasized { font-weight: bold } </style> hey <div class='emphasized'>watch out</div>",  scrubber: MyScrubber.new)

推荐阅读