I'm looking for best practice for creating a hyperlink which has both an icon and text.
I am currently using this in my view:
<%= link_to image_tag('icons/add.png', { :align => 'absmiddle', :border => 0, :size => '16x16', :alt => 'New education record', :title => 'New education record' }), new_education_path(@consultant) %> <%= link_to 'New education record', new_education_path(@consultant) %>
... but it feels really really unDRY!
Anyone got a DRYer solution please?
Add this to your helper class:
def link_to_image_with_caption image, text, url, img_options={}, link_options={} itag = image_tag(image, { :align => 'absmiddle', :border => 0, :size => '16x16', :alt => text, :title => text }.merge(img_options)) itag << " #{text}" link_to(itag, url_for(url), linkoptions) end
<%= link_to 'icons/add.png', 'New education record', new_education_path(@consultant) %>
If you don't want the :align, :border, and :size to be defaults, take them out of the helper and use:
<%= link_to 'icons/add.png', 'New education record', new_education_path(@consultant), :align => 'absmiddle', :border => 0, :size => '16x16' %>
If you need to add options to the link (i.e., the HTML of the <a> tag) such as a class, then:
<%= link_to 'icons/add.png', 'New education record', new_education_path(@consultant), { :align => 'absmiddle', :border => 0, :size => '16x16' }, :class => 'addlink' %>
You could also consider adding the image with CSS and just adding
-Rob
Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com