I have
@str = "<b>Hi</b>"
and in my erb view:
<%= @str %>
What will display on the page is: <b>Hi</b> when what I really want is Hi. What’s the ruby way to “interpret” a string as HTML markup?
Edit: the case where
@str = "<span class=\"classname\">hello</span>"
If in my view I do
<%raw @str %>
The HTML source code is <span class=\"classname\">hello</span> where what I really want is <span class="classname">hello</span> (without the backslashes that were escaping the double quotes). What’s the best way to “unescape” those double quotes?
UPDATE
For security reasons, it is recommended to use
sanitizeinstead ofhtml_safe.What’s happening is that, as a security measure, Rails is escaping your string for you because it might have malicious code embedded in it. But if you tell Rails that your string is
html_safe, it’ll pass it right through.OR
Using
rawworks fine, but all it’s doing is converting the string to a string, and then callinghtml_safe. When I know I have a string, I prefer callinghtml_safedirectly, because it skips an unnecessary step and makes clearer what’s going on. Details about string-escaping and XSS protection are in this Asciicast.