Ruby on Rails: how to render a string as HTML?
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 sanitize
instead of html_safe
.
<%= sanitize @str %>
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.
@str = "<b>Hi</b>".html_safe
<%= @str %>
OR
@str = "<b>Hi</b>"
<%= @str.html_safe %>
Using raw
works fine, but all it's doing is converting the string to a string, and then calling html_safe
. When I know I have a string, I prefer calling html_safe
directly, because it skips an unnecessary step and makes clearer what's going on. Details about string-escaping and XSS protection are in this Asciicast.
If you're on rails
which utilizes Erubis — the coolest way to do it is
<%== @str >
Note the double equal sign. See related question on SO for more info.