Reputation: 79512
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?
Upvotes: 119
Views: 170297
Reputation: 23939
Comparaison of the different methods:
> CGI::escapeHTML("quote ' double quotes \"")
=> "quote ' double quotes ""
> Rack::Utils.escape_html("quote ' double quotes \"")
=> "quote ' double quotes ""
> ERB::Util.html_escape("quote ' double quotes \"")
=> "quote ' double quotes ""
I wrote my own to be compatible with Rails ActiveMailer escaping:
def escape_html(str)
CGI.escapeHTML(str).gsub("'", "'")
end
Upvotes: 13
Reputation: 93
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 escape result[r].thtitle
in the confirm method, the Javascript would break:
<%= link_to_remote "#{result[r].thtitle}", :url=>{ :controller=>:resource,
:action =>:delete_resourced,
:id => result[r].id,
:th => thread,
:html =>{:title=> "<= Remove"},
:confirm => h("#{result[r].thtitle} will be removed"),
:method => :delete %>
<a href="#" onclick="if (confirm('docs: add column &apos;dummy&apos; will be removed')) { new Ajax.Request('/resource/delete_resourced/837?owner=386&th=511', {asynchronous:true, evalScripts:true, method:'delete', parameters:'authenticity_token=' + encodeURIComponent('ou812')}); }; return false;" title="<= Remove">docs: add column 'dummy'</a>
Note: the :html
title declaration is magically escaped by Rails.
Upvotes: 0
Reputation: 9177
An addition to Christopher Bradford's answer to use the HTML escaping anywhere,
since most people don't use CGI
nowadays, you can also use Rack
:
require 'rack/utils'
Rack::Utils.escape_html('Usage: foo "bar" <baz>')
Upvotes: 20
Reputation: 8884
ERB::Util.html_escape can be used anywhere. It is available without using require
in Rails.
Upvotes: 30
Reputation: 17516
In Ruby on Rails 3 HTML will be escaped by default.
For non-escaped strings use:
<%= raw "<p>hello world!</p>" %>
Upvotes: 80
Reputation: 2260
Checkout the Ruby CGI class. There are methods to encode and decode HTML as well as URLs.
CGI::escapeHTML('Usage: foo "bar" <baz>')
# => "Usage: foo "bar" <baz>"
Upvotes: 159
Reputation: 347216
You can use either h()
or html_escape()
, but most people use h()
by convention. h()
is short for html_escape()
in rails.
In your controller:
@stuff = "<b>Hello World!</b>"
In your view:
<%=h @stuff %>
If you view the HTML source: you will see the output without actually bolding the data. I.e. it is encoded as <b>Hello World!</b>
.
It will appear an be displayed as <b>Hello World!</b>
Upvotes: 16