Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: link_to image tag. how to add class to a tag

I am using link_to img tag like following

<%= link_to image_tag("Search.png", :border=>0, :class => 'dock-item'),  :action => 'search', :controller => 'pages'%><span>Search</span></a> 

Which results in following html

<a href="/pages/search"><img alt="Search" border="0" class="dock-item"  src="/images/Search.png?1264132800" /></a><span>Search</span></a>  

I want the class="dock-item" to go to the <a> tag instead of the img tag.

How can i change this?

Update:

<%= link_to image_tag("Search.png", :border=>0), :action => 'search',  :controller => 'pages', :class => 'dock-item' %> 

results in

<a href="/pages/search?class=dock-item"><img alt="Search" border="0"  src="/images/Search.png?1264132800" /></a>  
like image 342
Omnipresent Avatar asked Jan 22 '10 05:01

Omnipresent


1 Answers

hi you can try doing this

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, {class: 'dock-item'} 

or even

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, class: 'dock-item' 

note that the position of the curly braces is very important, because if you miss them out, rails will assume they form a single hash parameters (read more about this here)

and according to the api for link_to:

link_to(name, options = {}, html_options = nil) 
  1. the first parameter is the string to be shown (or it can be an image_tag as well)
  2. the second is the parameter for the url of the link
  3. the last item is the optional parameter for declaring the html tag, e.g. class, onchange, etc.

hope it helps! =)

like image 117
Staelen Avatar answered Sep 25 '22 23:09

Staelen