Sanitize gem不喜欢href属性中的冒号

时间:2011-05-12 05:12:07

标签: ruby-on-rails ruby sanitize

使用Sanitize gem,我正在清理一些HTML。在我的锚标签的href属性中,我希望解析以下内容:

<a href="#fn:1">1</a>

这是实施footnotes using the Kramdown gem所必需的。

但是,Sanitize似乎不喜欢href属性中的冒号。它只是输出<a>1</a>而是完全跳过href属性。

我的清理代码如下所示:

# Setup whitelist of html elements, attributes, and protocols that are allowed.
allowed_elements = ['h2', 'a', 'img', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'cite', 
  'blockquote', 'code', 'pre', 'dl', 'dt', 'dd', 'br', 'hr', 'sup', 'div']
allowed_attributes = {'a' => ['href', 'rel', 'rev'], 'img' => ['src', 'alt'], 
  'sup' => ['id'], 'div' => ['class'], 'li' => ['id']}
allowed_protocols = {'a' => {'href' => ['http', 'https', 'mailto', :relative]}}

# Clean text of any unwanted html tags.
html = Sanitize.clean(html, :elements => allowed_elements, :attributes => allowed_attributes, 
  :protocols => allowed_protocols)

有没有办法让Sanitize接受href属性中的冒号?

1 个答案:

答案 0 :(得分:3)

这是Sanitize默认做最安全的事情。它假定:之前的URL部分是协议(或RFC 1738术语中的方案),并且由于#fn不在协议白名单中,因此整个{{1} }属性已删除。

您可以通过向协议白名单添加href来允许此类网址:

#fn