public Method

AssetTagHelper.image_tag(source, options = {})

Contents:

Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory.

Options

You can add HTML attributes using the options. The options supports three additional keys for convenience and conformance:

  • :alt - If no alt text is given, the file name part of the source is used (capitalized and without the extension)
  • :size - Supplied as "{Width}x{Height}", so "30x45" becomes width="30" and height="45". :size will be ignored if the value is not in the correct format.
  • :mouseover - Set an alternate image to be used when the onmouseover event is fired, and sets the original image to be replaced onmouseout. This can be used to implement an easy image toggle that fires on onmouseover.

Examples

image_tag("icon")  # =>
  <img src="/images/icon" alt="Icon" />
image_tag("icon.png")  # =>
  <img src="/images/icon.png" alt="Icon" />
image_tag("icon.png", :size => "16x10", :alt => "Edit Entry")  # =>
  <img src="/images/icon.png" height="10" alt="Edit Entry" width="16" />
image_tag("/icons/icon.gif", :size => "16x16")  # =>
  <img src="/icons/icon.gif" height="16" alt="Icon" width="16" />
image_tag("/icons/icon.gif", :height => '32', :width => '32') # =>
  <img src="/icons/icon.gif" height="32" alt="Icon" width="32" />
image_tag("/icons/icon.gif", :class => "menu_icon") # =>
  <img src="/icons/icon.gif" alt="Icon" />
image_tag("mouse.png", :mouseover => "/images/mouse_over.png") # =>
  <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />
image_tag("mouse.png", :mouseover => image_path("mouse_over.png")) # =>
  <img src="/images/mouse.png" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" alt="Mouse" />

Source Code

# File action_view/helpers/asset_tag_helper.rb, line 397
def image_tag(source, options = {})
  options.symbolize_keys!

  options[:src] = path_to_image(source)
  options[:alt] ||= File.basename(options[:src], '.*').split('.').first.to_s.capitalize

  if size = options.delete(:size)
    options[:width], options[:height] = size.split("x") if size =~ %r{^\d+x\d+$}
  end

  if mouseover = options.delete(:mouseover)
    options[:onmouseover] = "this.src='#{image_path(mouseover)}'"
    options[:onmouseout]  = "this.src='#{image_path(options[:src])}'"
  end

  tag("img", options)
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.