DRY question - image_tag :alt and :title the same

Hello,

I have the following: image_tag('show.png', :alt => 'show article', :title => 'show article', :border => 0)

Is it possible that I don´t need to have "=> 'show article'" twice in this row? e.g. something similar to this pseudo code: (:alt, :title) => 'show article'.

Short version: As far as tooltips go, :alt = IE and :title = FF. You’ll need both to display a tooltip across browsers. There are differences between them but I’m not sure if you’re looking for that information so much as “do I need both”. :slight_smile:

RSL

short answer, no there is no way to specify the value of 2 attributes the way you describe.

you could write a helper tho

def my_image_tag(source, options = {})   options.symbolize_keys!

  # if there is an alt attribute but no title attribute   options[:title] = options[:alt] if options.has_key?(:alt) && !options.has_key?(:title)

  # if there is a title attribute but no alt attribute   options[:alt] = options[:title] if options.has_key?(:title) && !options.has_key?(:alt)

  # don't change anything if both or none are specified

  image_tag(source, options) end

not tested, but should work, examples below

<%= my_image_tag(..., { :alt => 'alt tag' }) %> <img src="..." alt="alt tag", title="alt tag"/>

<%= my_image_tag(..., { :title => 'title tag' }) %> <img src="..." alt="title tag", title="title tag"/>

<%= my_image_tag(...) %> <img src="..."/>

<%= my_image_tag(..., { :alt => 'alt tag', :title => 'title tag' }) %> <img src="..." alt="alt tag", title="title tag"/>

Short version: As far as tooltips go, :alt = IE and :title = FF. You'll need both to display a tooltip across browsers.

<...>

No. IE will display alt attribute as tooltip, Firefox won't (and sholudn't). However, they will both display title attribute. Alt is supposed to be used when image cannot be shown - not available on server, user has disabled images, text-only browser.

Regards, Rimantas

Heh. You caught me. I didn’t mention that IE respects :title [because I didn’t think it necessary since I was talking about specifically about tooltips alt vs. title ]. Please don’t embarrass me further by pointing out that other browsers than IE and FF support these tags as well. :wink:

RSL

I thought there is a ruby way of doing this. Now I implemented a small plugin which extends ActionView::Base, ActionView::Helpers::TagHelper tag method to have a "single point of change" (DRY) - because I needed it for image_tag, image_submit_tag, etc. Thank you for your help.

Further to Rimantas explanation, browser implementation isn't really the issue here as the two attributes are intended for different purposes and setting them to the same value is incorrect; you can find a good outline of the issues @ The alt and title attributes | 456 Berea Street