【问题标题】:Remove tags and their content in Rails在 Rails 中删除标签及其内容
【发布时间】:2016-09-28 11:35:01
【问题描述】:

如何在 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>

【问题讨论】:

  • 您只想删除此标签的标签和内容,还是想要特定标签?也许你可以使用nokogiri 来解析特定的标签。
  • 同样的事情对我有用

标签: ruby-on-rails sanitize


【解决方案1】:

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>  "

如果例如您只想删除 &lt;script&gt; 之类的标签并保持其他所有内容不变,您可以执行以下操作:

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 "

请注意,最后一个&lt;div&gt; 的内容仍然存在,因为它没有包含在remove_contents 数组中,但它的&lt;div&gt; 标记已被删除(Sanitize::Config::BASIC 的工作原理就是这样)。将Sanitize::Config::BASIC 替换为Sanitize::Config::RELAXED 以获得较少限制的过滤规则,这将在此示例中保留&lt;div&gt; 标记。

虽然我找到的唯一文档是 in the code itself,但还有许多其他可能。

【讨论】:

  • 是否可以删除 script 但不触及其他 HTML?因为我想避免将所有这些标签传递给元素选项。谢谢。
  • 所以对于你的第二个代码块,你只需要&lt;p&gt;Hello world&lt;/p&gt;
  • 试试这个:Sanitize.fragment(html, Sanitize::Config.merge(Sanitize::Config::BASIC, remove_contents: true))
  • 在上面添加了一个示例,删除script,同时不触及其他内容。
  • 这里:Sanitize.fragment(@content, Sanitize::Config.merge(Sanitize::Config::BASIC, elements: Sanitize::Config::RELAXED[:elements] - ['style'], remove_contents: ['style']))
猜你喜欢
  • 2011-10-10
  • 2020-11-11
  • 1970-01-01
  • 2018-10-28
  • 2014-06-11
  • 1970-01-01
  • 2010-12-03
  • 2022-11-21
  • 2014-12-10
相关资源
最近更新 更多