views:

6891

answers:

4

Yay, silly question time.

So I have an untrusted string that I simply want to show as text in an html page. All I need to do is escape the chars '<' and '&' as html entities.

The less fuss the better. I'm using utf8 and don't need no other stinking entities for accented letters and so on.

Is there anything built-in in ruby or rails, or should I roll my own?

+6  A: 

The h helper method!

<%=h "<p> will be preserved" %>
Trevor Bramble
Well, it also escapes >, which is unnecessary, but it'll do.
kch
You can use parentheses to print some with h and some without. <%= h("<p") + ">" %>
Trevor Bramble
Now that would be silly. I don't care much if it gets escaped or not. I'm just noting it's not required per the html specs.
kch
It's *occasionally* required in XHTML due to the XML spec's rather annoying insistence that ‘]]>’ be kept out of text (see the ‘CharData’ production). This makes it generally easier (and harmless) to always escape it.
bobince
+3  A: 

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 &lt;b&gt;Hello World!&lt;/b&gt;.

It will appear an be displayed as <b>Hello World!</b>

Brian R. Bondy
A: 

doesn't appear to encode double-quotes.

+1  A: 

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 &quot;bar&quot; &lt;baz&gt;"
Christopher Bradford