I have an untrusted string that I want to show as text in an HTML page. I need to escape the chars '<
' and '&
' as HTML entities. The less fuss the better.
I'm using UTF8 and don't need other entities for accented letters.
Is there a built-in function in Ruby or Rails, or should I roll my own?
h()
is also useful for escaping quotes.For example, I have a view that generates a link using a text field
result[r].thtitle
. The text could include single quotes. If I didn't escaperesult[r].thtitle
in the confirm method, the Javascript would break:Note: the
:html
title declaration is magically escaped by Rails.ERB::Util.html_escape can be used anywhere. It is available without using
require
in Rails.Comparaison of the different methods:
I wrote my own to be compatible with Rails ActiveMailer escaping:
The
h
helper method:Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.
In Ruby on Rails 3 HTML will be escaped by default.
For non-escaped strings use: