确切地说,我不知道这些之间的区别。我读了这个
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html
但不要得到确切的区别。谁能告诉我有什么区别?
确切地说,我不知道这些之间的区别。我读了这个
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html
但不要得到确切的区别。谁能告诉我有什么区别?
sanitize
正在使用白名单消毒剂。 strip_tags
剥离所有标签。
相比:
[64] pry(main)> sanitize "hello <h1>h1</h1> <b>b</b>"
=> "hello <h1>h1</h1> <b>b</b>"
[65] pry(main)> strip_tags "hello <h1>h1</h1> <b>b</b>"
=> "hello h1 b"
如果您不提供任何列入白名单的标签,sanitize
则默认允许以下标签。
[66] pry(main)> ActionView::Base.white_list_sanitizer.allowed_tags.to_a * ', '
=> "strong, em, b, i, p, code, pre, tt, samp, kbd, var, sub, sup,
dfn, cite, big, small, address, hr, br, div, span, h1, h2, h3,
h4, h5, h6, ul, ol, li, dl, dt, dd, abbr, acronym, a, img,
blockquote, del, ins"
如果您提供自己的白名单标签,则它们会覆盖默认标签。
[67] pry(main)> sanitize "hello <h1>h1</h1> <b>b</b>", tags: %w(b)
=> "hello h1 <b>b</b>"
sanitize
和之间的另一个区别strip_tags
是sanitize
删除了一些标签的内容(中间的东西),特别是<script>
标签。
相比:
[68] pry(main)> sanitize "a<script>alet('foo')</script>"
=> "a"
[69] pry(main)> strip_tags "a<script>alet('foo')</script>"
=> "aalet('foo')"
此外,sanitize
对某些字符进行 html-escape,但strip_tags
没有。
[70] pry(main)> sanitize "< &"
=> "< &"
[71] pry(main)> strip_tags "< &"
=> "< &"
此外,它们处理嵌套标签的方式不同。比较以下,
[73] pry(main)> sanitize "some<<b>script>alert('hello')<</b>/script>", tags: []
=> "some<script>alert('hello')</script>"
[74] pry(main)> strip_tags "some<<b>script>alert('hello')<</b>/script>"
=> "somealert('hello')"
使用 sanitize 可以允许一些 HTML 标签或类,而 strip_tags 不能。它做同样的事情。检查代码https://github.com/rails/rails/blob/76a0b1028e312b6c3c00a50b4a09d68c23b5e713/actionview/lib/action_view/helpers/sanitize_helper.rb#L80