Tuesday, May 6, 2014

h method Rails

Class Public methods

h(s)
Alias for: html_escape

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:
<%=h @person.name %>

puts html_escape('is a > 0 & a < 10?')
# => is a &gt; 0 &amp; a &lt; 10?

Also aliased as: h

html_escape_once(s)
A utility method for escaping HTML without affecting existing escaped entities.
html_escape_once('1 < 2 &amp; 3')
# => "1 &lt; 2 &amp; 3"

html_escape_once('&lt;&lt; Accept & Checkout')
# => "&lt;&lt; Accept &amp; Checkout"


http://www.webbydude.com/posts/9-the-h-helper-in-rails-3

The h() helper in Rails 3

How to escape/unescape HTML tags in Rails 3

Written by: David Zhu on November 06, 2010 22:35

Back in Rails 2.x, the h() helper escapes HTML input from the user, and renders it out as plain text.

For example, if I render out:

<%= @post.body %>


and the user has inputted HTML tags in the body field, like so:

        Hello <strong>World!</strong>

It will render out as:

        Hello World!

However, by adding the h() helper like so:

<%= h(@post.body) %>


it will escape all HTML and render out as

        Hello <strong>World!</strong>

just like what the user wrote. That's all good, but it's different in Rails 3.

Rails 3

In Rails 3, the h() helper is automatically appended, or in other words, it automatically escapes all code tags. There is no need to write h() anymore, it does it automatically.

However, what if you don't want to escape any HTML? The raw() helper does that:

<%= raw(@post.body) %>


By adding the raw() helper, all HTML and code tags that the user submits will be analyzed through the browser as real code. So by writing

        Hello <strong>World!</strong>

it will actually render out

        Hello World!

just as if you did not include the h() back in Rails 2.

No comments:

Post a Comment