I have two pieces of code in my view:
<%= sanitize('<h3>winter</h3>') %>
<%= '<h3>winter</h3>'.html_safe %>
And they both seem to result in encoding html tags in a string provided. What is the difference between them and when should I use either?
Sanitize is an allowlist-based HTML and CSS sanitizer. It removes all HTML and/or CSS from a string except the elements, attributes, and properties you choose to allow.
html_safe actually "sets the string" as HTML Safe (it's a little more complicated than that, but it's basically it). This way, you can return HTML Safe strings from helpers or models at will. h can only be used from within a controller or view, since it's from a helper. It will force the output to be escaped.
Safe HTML is a module that filter the input before the content is stored in the database. Unlike Drupal basic filtering system, Safe HTML filter the form post and perform code cleaning before the content is stored on the site backend.
Those are two very different methods.
a = a.html_safe
will just mark string a
as 'html_safe' and treat it as such afterwards (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
, on the other hand, will html encode all tags and strip all attributes that are not specifically allowed (you can add/remove allowed tags and attributes if you want). Notice that user input is sanitized by default unless you specifically allowed html-markup with raw
(http://apidock.com/rails/ActionView/Helpers/OutputSafetyHelper/raw), which, by the way, uses html_safe
to mark it as such.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With