Ruby on Rails:.html_safe和sanitize()之间的区别

时间:2014-05-14 16:11:10

标签: ruby-on-rails-4 sanitize difference html-safe

我认为我有两段代码:

<%= sanitize('<h3>winter</h3>') %>

<%= '<h3>winter</h3>'.html_safe %>

它们似乎都导致在提供的字符串中编码html标签。 它们之间有什么区别,我应该何时使用它们?

1 个答案:

答案 0 :(得分:16)

这是两种截然不同的方法。

a = a.html_safe只会将字符串a标记为“html_safe”,然后将其视为(Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed. It is your responsibility to ensure that the string contains no malicious content. This method is equivalent to the raw helper in views. It is recommended that you use sanitize instead of this method. It should never be called on user input.)

另一方面,

a.sanitize将对所有标记进行html编码并删除所有未明确允许的属性(如果需要,可以添加/删除允许的标记和属性)。请注意,默认情况下会对用户输入进行清理,除非您明确允许使用rawhttp://apidock.com/rails/ActionView/Helpers/OutputSafetyHelper/raw)的html标记,顺便说一下,使用html_safe标记它。