Suppose I have the following string
@x = "<a href='#'>Turn me into a link</a>"
In my view, I want a link to be displayed. That is, I don’t want everything in @x to be unescaped and displayed as a string. What’s the difference between using
<%= raw @x %>
<%= h @x %>
<%= @x.html_safe %>
?
Considering Rails 3:
html_safeactually “sets the string” as HTML Safe (it’s a little more complicated than that, but it’s basically it). This way, you can return HTML Safe strings from helpers or models at will.hcan only be used from within a controller or view, since it’s from a helper. It will force the output to be escaped. It’s not really deprecated, but you most likely won’t use it anymore: the only usage is to “revert” anhtml_safedeclaration, pretty unusual.Prepending your expression with
rawis actually equivalent to callingto_schained withhtml_safeon it, but is declared on a helper, just likeh, so it can only be used on controllers and views.“SafeBuffers and Rails 3.0” is a nice explanation on how the
SafeBuffers (the class that does thehtml_safemagic) work.