Ruby on Rails: difference between .html_safe and sanitize()
Asked Answered
B

1

20

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?

Blossom answered 14/5, 2014 at 16:11 Comment(1)
Note that .sanitize was removed from rails in 5.1 (github.com/rails/rails/issues/28947)Ecumenicity
B
30

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.

Blossom answered 23/3, 2015 at 8:55 Comment(2)
So is sanitize('<h3>winter</h3>').html_safe redundant?Dialogist
@Dialogist Yes indeedHawthorne

© 2022 - 2024 — McMap. All rights reserved.