Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using image_tag with srcset attribute?

I try to use an srcset attribute inside an image_tag but I can not make it work.

Im not sure if it is a syntax error or it generally does not work in an image_tag.

Is it possible to use a srcset attribute in an image_tag?

If yes, how?, and if not why not and is there a workaround?

<%= link_to(image_tag("logo.png", alt: "logo", :id => "logo"), root_path) %>
like image 542
trickydiddy Avatar asked Jul 27 '17 20:07

trickydiddy


1 Answers

Instead of adding the image_tag to the link_to "name" option you can use open up block and pass your image there.

If you want to use a srcset attribute you could extend the functionality of image_tag by creating a helper:

def image_set_tag(source, srcset = {}, options = {})
  srcset = srcset.map { |src, size| "#{path_to_image(src)} #{size}" }.join(', ')
  image_tag(source, options.merge(srcset: srcset))
end

It joins each size by comma, so then you can do:

<%= link_to root_path do %>
  <%= image_set_tag 'logo.jpg', { 
     'logo_640.jpg'  => '640w', 
     'logo_1024.jpg' => '1024w', 
     'logo_1980.jpg' => '1980w' 
   }, sizes: '100vw', alt: 'logo', id: 'logo' %>
<% end %>

As you can see, the changes introduced in ActionView::Helpers::AssetTagHelper#image_tag in the 5.2.1 Rails version allows you to pass the srcset option, with a hash or an array of 2D arrays containing the different responsive versions of your image:

image_tag("icon.png", srcset: { "icon_2x.png" => "2x", "icon_4x.png" => "4x" })
# => <img src="/assets/icon.png" srcset="/assets/icon_2x.png 2x, /assets/icon_4x.png 4x">

image_tag("pic.jpg", srcset: [["pic_1024.jpg", "1024w"], ["pic_1980.jpg", "1980w"]], sizes: "100vw")
# => <img src="/assets/pic.jpg" srcset="/assets/pic_1024.jpg 1024w, /assets/pic_1980.jpg 1980w" sizes="100vw">

So, if you're using a more recent Rails version, you can just use image_tag instead of writing your own implementation.

like image 94
Sebastian Palma Avatar answered Oct 01 '22 15:10

Sebastian Palma