Home » Ruby » What is the meaning of “h” in “<%=h [ …] %>”?

What is the meaning of “h” in “<%=h [ …] %>”?

Posted by: admin November 30, 2017 Leave a comment

Questions:

When I generate a default scaffold, the display tags on show.html.erb have

<%=h @broker.name %>

I know the difference between <% and <%=. What’s the “h” do?

Answers:

html escape. It’s a method that converts things like < and > into numerical character references so that rendering won’t break your html.

Questions:
Answers:

<%=h is actually 2 things happening. You’re opening an erb tag (<%=) and calling the Rails method h to escape all symbols.

These two calls are equivalent:

<%=h person.first_name %>
<%= h(person.first_name) %>

The h method is commonly used to escape HTML and Javascript from user-input forms.

Questions:
Answers:

h is a method alias for html_escape from the ERB::Util class.

Questions:
Answers:

There is also a method in Rack to escape HTML Rack::Utils.escape_html in case you are in Metal and want to escape some HTML.

Questions:
Answers:

Way late to the party but I’m adding a further explanation to what html_escape is doing to hopefully help other noobs like myself understand what’s happening. Rails 3 and later automatically escape all output now and so there are much fewer situations where html_escape aka h() will be needed. The most notable of which is when you intend to use the html_safe method when building links with html in a presenter class etc. For example:

#some_view.html.erb
<span><%= @user.name %></span>  #This is 100% fine and will be automatically escaped by Rails 3+
#Output =>  <span>Brian Kunzig</span>

#Now say we want a link with html that we need preserved!  OMG WHAT ARE DO??
<%=link_to "<span><i class='fa fa-user'></i>#{@user.name}</span>".html_safe  #DANGER!!!

The link above can cause serious problems and open you up to all sorts of xss (cross-site scripting) attacks. The most simple example, if a user saved their name as "<script>alert('omg');</script>" and you used html_safe on it, it will cause any page rendering their supposed name to get an alert saying ‘omg’! This is a major problem. To avoid this do:

<%=link_to "<span><i class='fa fa-user'></i>#{h(@user.name)}</span>".html_safe #Winning!

By escaping the potentially tainted data supplied by a user we’re homefree!