grabury
grabury

Reputation: 5559

How to display an image using image_tag in Rails

I'm trying to add my first image to my html.erb page.

I added the image to the assets image folder and then added the following to the page

<%= image_tag("logo.png") %>

and a long number is displayed instead of the image.

<img alt="Logo 0832b7f341b4a86866d5ebbefb333a263da300acd97a6eccbc25263b235ccdc5" src="/assets/logo-0832b7f341b4a86866d5ebbefb333a263da300acd97a6eccbc25263b235ccdc5.png">

and if I use the following

<%= link_to(image_tag("logo.png", :alt => "logo"), "/", class: "navbar-brand navbar-brand-img") %>

Only the words "logo" are displayed.

Upvotes: 0

Views: 3041

Answers (3)

Almir Sarajčić
Almir Sarajčić

Reputation: 1570

You can find the explanation on APIdock:

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 two 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.

The numbers you see there are added to the filenames during deployment as a caching mechanism - browsers can cache these files indefinitely since the filenames will change each time they are changed.

To precompile these files and add these numbers to the filenames use rake assets:precompile command.

Upvotes: 1

Gaurav Gupta
Gaurav Gupta

Reputation: 475

Change your code as below:

<%= link_to image_tag("logo.png", :alt => "logo" , class:"navbar-brand navbar-brand-img"), "/" %>

Hope it will help you.

Upvotes: 0

Shalev Shalit
Shalev Shalit

Reputation: 1963

When you use the asset pipeline, it add md5 to the image link.

Provided that the pipeline is enabled within your application (and not disabled in the current environment context), this file is served by Sprockets. If a file exists at public/assets/rails.png it is served by the web server.

Alternatively, a request for a file with an MD5 hash such as public/assets/rails-af27b6a414e6da00003503148be9b409.png is treated the same way. How these hashes are generated is covered in the In Production section later on in this guide.

see more in coding-links-to-assets

Upvotes: 0

Related Questions