Blog



Ruby on Rails: link_to and image_tag

Yet another quick code reminder as I always forget the syntax, this time to combine link_to and image_tag in Ruby on Rails.

So if  you want an image_tag (here “logo.jpg”) to redirect the user to another URL (in this case, the root of the site) when clicked, simply use the combination link_to and image_tag below.

Link_to an image_tag from the public folder

<%= link_to(image_tag("logo.jpg", :alt => "logo", :title => "Home"), "/") %>

The above example assumes you have the image “logo.jpg” within the public folder.
This will create the HTML code below:

<a title="home" href="/"><img src="logo.jpg" alt="logo" /></a>

Link_to and image_tag from your assets


>

In the case you need to access your “logo.jpg” from /app/assets/images, the code would be as follow:

<%= link_to(image_tag("/assets/logo.jpg", :alt => "logo", :title => "Home"), "/") %>

This will create the HTML code below:

<a title="home" href="/"><img src="/assets/logo.jpg" alt="logo" /></a>

Adding classes and ids to your link_to and image_tag

You can also add :class => “” and/or :id => “” on either the link_to or image_tag as below:

<%= link_to(image_tag("logo.jpg", :alt => "logo", :title => "Home", :class=>"images", :id=>"logo"), "/", :class=>"links", :id=>"logo_link") %>

This code will produce the HTML code below:

<a id="logo_link" title="home" href="/"><img id="logo" src="/assets/logo.jpg" alt="logo" /></a>

See more info on the official Rubyonrails


IT Support Newcastle is brought to you by Transcendit Ltd, contact us on 0191 482 0444