Sanitize

Sanitize是一个基于white_list的ruby html的清道夫,他的功能非常的强大,用起来也非常的简单

首先,在命令行下安装它:


sudo gem install sanitize

然后我们就可以通过以下的方式来调用他:

1
2
3
4
5
6
require 'rubygems'
require 'sanitize'

html = '<b><a href="http://foo.com/">foo</a></b><img src="http://foo.com/bar.jpg" />'

Sanitize.clean(html) # => 'foo'

他默认是将所有的html 标签都删除的,当然我们可以通过他内建的标准配置项来配置我们要删除的标签,主要有:

1
2
3
4
5
6
7
8
Sanitize.clean(html, Sanitize::Config::RESTRICTED)
# => '<b>foo</b>'

Sanitize.clean(html, Sanitize::Config::BASIC)
# => '<b><a href="http://foo.com/" rel="nofollow">foo</a></b>'

Sanitize.clean(html, Sanitize::Config::RELAXED)
# => '<b><a href="http://foo.com/">foo</a></b><img src="http://foo.com/bar.jpg" />'

如果标准的内建配置项还不能满足你的需求,你可以自己来扩展配置项,下面我们将具体来说说怎么自定义扩展

1
2
3
Sanitize.clean(html, :elements => ['a', 'span'],
      :attributes => {'a' => ['href', 'title'], 'span' => ['class']},
      :protocols => {'a' => {'href' => ['http', 'https', 'mailto']}})

上面是一个完整的自定义格式,先来看看:elements ,他是用来设定操作的对象,sanitize有以下一些操作对象

1
2
3
4
5
:elements => [
    'a', 'b', 'blockquote', 'br', 'cite', 'code', 'dd', 'dl', 'dt', 'em',
    'i', 'li', 'ol', 'p', 'pre', 'q', 'small', 'strike', 'strong', 'sub',
    'sup', 'u', 'ul'
  ]

再看看:attributes,他是用来设定操作对象的属性,如果我们的操作对象(element)没有这些属性将会并清理掉,有的话就跳过去检测协议(protocols)条件

1
2
3
4
5
:attributes => {
    'a'          => ['href', 'title'],
    'blockquote' => ['cite'],
    'img'        => ['alt', 'src', 'title']
  }

如果上述属性并不是你想要的,你可以通过:add_attributes来添加属性,从而来限定操作对象,如下

1
2
3
:add_attributes => {
    'a' => {'rel' => 'nofollow'}
  }

最后来看看协议:protocols,我们可以通过设定element的attributes的协议类型,从而来限定操作的对象,如果属性中包含这个协议将不会被清除,否则这个html元素将被清掉

1
2
3
4
:protocols => {
    'a'   => {'href' => ['ftp', 'http', 'https', 'mailto']},
    'img' => {'src'  => ['http', 'https']}
  }

如果你要用到相对路径,他并没有任何协议,你可以通过以下方式来搞定它

1
2
3
:protocols => {
    'a' => {'href' => ['http', 'https', :relative]}
  }

更加详细的内容你可以查看sanitize的源文件,点击 sanitize rdoc


Wiki首页 | 查看所有 | 编辑 | 输出到博客 | 历史版本