It provides a concise API to generate links. It’s a public method called #link_to, that can be used both in views and templates.

Usage

It accepts two mandatory and one optional arguments. The first is the content of the tag, the second is the path, an the third is a Hash that represents a set of HTML attributes that we may want to specify.

  1. <%= link_to 'Home', '/' %>
  2. <%= link_to 'Profile', routes.profile_path, class: 'btn', title: 'Your profile' %>
  3. <%=
  4. link_to(routes.profile_path, class: 'avatar', title: 'Your profile') do
  5. img(src: user.avatar.url)
  6. end
  7. %>

Output:

  1. <a href="/">Home</a>
  2. <a href="/profile" class="btn" title="Your profile">Profile</a>
  3. <a href="/profile" class="avatar" title="Your profile">
  4. <img src="/images/avatars/23.png">
  5. </a>

Alternatively, the content can be expressed as a given block.

  1. module Web
  2. module Views
  3. module Books
  4. class Show
  5. include Web::View
  6. def look_inside_link
  7. url = routes.look_inside_book_path(id: book.id)
  8. link_to url, class: 'book-cover' do
  9. html.img(src: book.cover_url)
  10. end
  11. end
  12. end
  13. end
  14. end
  15. end

Template:

  1. <%= look_inside_link %>

Output:

  1. <a href="/books/1/look_inside" class="book-cover">
  2. <img src="https://cdn.bookshelf.org/books/1/full.png">
  3. </a>

Security

There are two aspects to consider when we use links in our markup: whitelisted URLs and escaped attributes. Please visit the Markup Escape section for a detailed explanation.