How to render an html_safe string escaped

Posted Over 8 years ago. Visible to the public.

Once Rails knows a given string is html_safe, it will never escape it. However, there may be times when you still need to escape it. Examples are some safe HTML that you pipe through JSON, or the display of an otherwise safe embed snippet.

There is no semantically nice way to do this, as even raw and h do not escape html_safe strings (the former just marks its argument as html_safe). You need to turn your string into an unsafe string to get the escaping love from Rails:

embed = javascript_tag('var foo = 1337;') # This is an html_safe SafeBuffer
embed.to_str # This is a plain, unsafe String
Dominik Schöler
Last edit
Over 8 years ago
Dominik Schöler
License
Source code in this card is licensed under the MIT License.
Posted by Dominik Schöler to makandra dev (2016-01-12 08:24)