Ruby on Rails: how to render a string as HTML?

Tim picture Tim · Jan 2, 2011 · Viewed 166.2k times · Source

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?

Answer

Jacob picture Jacob · Jan 2, 2011

UPDATE

For security reason, it is recommended to use sanitize instead of html_safe. Link


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 it clearer what's going on. Details about string-escaping and XSS protection are in this Asciicast.