How to Add an HTML Tag Inside a Ruby on Rails link_to Helper

July 04, 2012

Recently I was modifying a twitter bootstrap theme and had to create code that looked something like this for my navigation menu bar:

<a href="/contact">
  <i class="icon-envelope"></i>
  Contact
</a>

The idea here was to display an “envelope icon” next to the contact menu option. So I needed to insert another tag within the “a” tag.

The typical link_to syntax

Typically, in a rails .html.erb view, you would do something like this:

<%= link_to "Home", root_path %>

And it would produce html output that looked like this:

<a href="/">Home</a>

You can specify other html options such as :class or :id, but I didn’t know how to specify a tag within the “a” tag.

But you can do this by realizing link_to can take a block

Here’s the solution I went with:

<%= link_to contact_path do %>
  <i class="icon-envelope"></i>
  Contact
<% end %>

And here’s the output, exactly what I wanted:

<a href="/contact">
  <i class="icon-envelope"></i>
  Contact
</a>

Profile picture

Written by Bruce Park who lives and works in the USA building useful things. He is sometimes around on Twitter.