method

image_tag

image_tag(source, options={})
public

Returns an HTML image tag for the source. The source can be a full path or a file.

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}” or “{Number}”, so “30x45” becomes width=“30” and height=“45”, and “50” becomes width=“50” and height=“50”. :size will be ignored if the value is not in the correct format.

Examples

image_tag("icon")
# => <img alt="Icon" src="/assets/icon" />
image_tag("icon.png")
# => <img alt="Icon" src="/assets/icon.png" />
image_tag("icon.png", size: "16x10", alt: "Edit Entry")
# => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
image_tag("/icons/icon.gif", size: "16")
# => <img src="/icons/icon.gif" width="16" height="16" alt="Icon" />
image_tag("/icons/icon.gif", height: '32', width: '32')
# => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
image_tag("/icons/icon.gif", class: "menu_icon")
# => <img alt="Icon" class="menu_icon" src="/icons/icon.gif" />

4Notes

Using a block with image_tag

hardbap · Sep 30, 20111 thank

HTML5 officially supports block-level elements in the anchor tag and Rails 3 allows you to pass a block to image_tag:

<%= image_tag(some_path) do %> <%= content_tag(:p, "Your link text here") <% end %>

watch out for urls with &

grosser · Jul 10, 2008

image_tag('x.com/aaa?a=1&b=2') = x.com/aaa?a=1&b=2

By images's sub dirctionary to img tag

RobinWu · Oct 31, 2008

=== image_tag("icons/edit.png") # => edit

Specify your own template

Ramon · Mar 10, 2010

You can specify you own template this way:

def notice
...
@template = "some_other_name.html.erb"
end