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 %>
?
The best safe way is:
<%= sanitize @x %>
It will avoid XSS!
The difference is between Rails’
html_safe()
andraw()
. There is an excellent post by Yehuda Katz on this, and it really boils down to this:Yes,
raw()
is a wrapper aroundhtml_safe()
that forces the input to String and then callshtml_safe()
on it. It’s also the case thatraw()
is a helper in a module whereashtml_safe()
is a method on the String class which makes a new ActiveSupport::SafeBuffer instance — that has a@dirty
flag in it.Refer to "Rails’ html_safe vs. raw".
I think it bears repeating:
html_safe
does not HTML-escape your string. In fact, it will prevent your string from being escaped.will put:
into your HTML source (yay, so safe!), while:
will pop up the alert dialog (are you sure that's what you want?). So you probably don't want to call
html_safe
on any user-entered strings.html_safe
:Marks a string as trusted safe. It will be inserted into HTML with no additional escaping performed.
raw
:raw
is just a wrapper aroundhtml_safe
. Useraw
if there are chances that the string will benil
.h
alias forhtml_escape
:A utility method for escaping HTML tag characters. Use this method to escape any unsafe content.
In Rails 3 and above it is used by default so you don't need to use this method explicitly
In Simple Rails terms:
h
remove html tags into number characters so that rendering won't break your htmlhtml_safe
sets a boolean in string so that the string is considered as html saveraw
It converts to html_safe to stringConsidering Rails 3:
html_safe
actually "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.h
can 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_safe
declaration, pretty unusual.Prepending your expression with
raw
is actually equivalent to callingto_s
chained withhtml_safe
on 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
SafeBuffer
s (the class that does thehtml_safe
magic) work.