Saturday, August 29, 2009

What is the 'h' for in rails erb?

Often you see code like:

<%=h @person.name %>

The h doesn't seem to do anything if you take it out! The h is actually important, it is the html_escape. See the documentation:

http://api.rubyonrails.org/classes/ERB/Util.html

Here is a brief quote from the docs:

html_escape(s)

A utility method for escaping HTML tag characters. This method is also aliased as h.

In your ERb templates, use this method to escape any unsafe content. For example:

puts html_escape("is a > 0 & a < 10?")
# => is a > 0 & a < 10?

No comments: