Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: link_to and image_tag

How can I have an image tag linking to the file background.jpg in my public/images and when clicked on redirect the user to the root_url (So the content of the page is in a container and if the user clicks on the background image are redirected to home?) Thanks!

like image 314
Coxn Avatar asked Aug 21 '11 03:08

Coxn


2 Answers

Sure:

<%= link_to(image_tag("background.jpg", :alt => "home image", :width => 100, :height => 100, :title => "Click here to return to Home") "/") %>
like image 146
jschorr Avatar answered Oct 24 '22 18:10

jschorr


Most of rails tag helpers accept a block, which means you can use do to simplify your life. Here I use a block with link_to:

<%= link_to root_url do %>
  <%= image_tag "background.jpg" %>
<% end %>

In this case, link_to expects the next parameter to be the path and the block emits what the anchor wraps.

In general I try to keep to the one tag helper per line rule unless its super trivial, so prefer this technique when the line would otherwise become crowded. An advantage to doing it this way is since tags are on different lines, errors are easier to identify.

If you need other options to go with it, add them like you usually would. For example I'll add a css class:

<%= link_to root_url, :class => 'imagelink' do %>
  ...
like image 31
IAmNaN Avatar answered Oct 24 '22 20:10

IAmNaN