删除 Rails 中的标签及其内容

Remove tags and their content in Rails

如何删除 Rails 中的某些标签及其内容?

我尝试了 sanitizestrip_tags,但他们只是删除了标签并保留了内容。

<%= raw sanitize(@content, :tags => ['h1','h2','h3','h4','h5','h6','p','ul','ol','li','small','b','strong','em','i','u']) %>

所以如果我有这个:

<script>alert('test js');</script>
<p>Hello world</p>

我想成为:

<p>Hello world</p>

此时变为:

alert('test js');
<p>Hello world</p>

Sanitize 有一个 remove_contents 选项,您可以使用它。

来自测试代码:

Sanitize.fragment('foo bar <div>baz<span>quux</span></div>',
  :remove_contents => true
)
#=> 'foo bar   '

参见test example

对于上述情况,您可以在 remove_contents 的值中指定要删除的标签,如下所示:

Sanitize.fragment("<script>alert('test js');</script><p>Hello world</p>",
  remove_contents: ["script"]
)
#=> " Hello world "

或者,您可以指定要保留的元素并删除其他所有元素,如下所示:

html = "<strong>foo</strong><div>bar</div>"
Sanitize.fragment(html,
  elements: ['h1','h2','h3','h4','h5','h6','p','ul','ol','li','small','b','strong','em','i','u'],
  remove_contents: true
)
#=> "<strong>foo</strong>  "

如果例如你只想删除像 <script> 这样的标签并保持其他一切不变,你可以这样做:

html = "<strong>foo</strong><script>bar</script><p>baz</p><div>foobar</div>"
Sanitize.fragment(html,
  Sanitize::Config.merge(Sanitize::Config::BASIC, remove_contents: ['script'])
)
#=> "<strong>foo</strong><p>baz</p> foobar "

这里注意最后一个<div>的内容因为没有包含在remove_contents数组中,所以它的<div>标签被移除了(这就是Sanitize::Config::BASIC 有效)。将 Sanitize::Config::BASIC 替换为 Sanitize::Config::RELAXED 以获得限制性较低的过滤规则,这将在本例中保留 <div> 标签。

很多其他的事情也是可能的,尽管我找到的唯一文档是 in the code itself