Skip to content

Instantly share code, notes, and snippets.

@youngbrioche
Last active February 8, 2024 08:15
Show Gist options
  • Save youngbrioche/4fc71c8d09646567111f to your computer and use it in GitHub Desktop.
Save youngbrioche/4fc71c8d09646567111f to your computer and use it in GitHub Desktop.
Responsive images helper using srcset in Rails
module ImagesHelper
# Acts as a thin wrapper for image_tag and generates an srcset attribute for regular image tags
# for usage with responsive images polyfills like picturefill.js, supports asset pipeline path helpers.
#
# image_set_tag 'pic_1980.jpg', { 'pic_640.jpg' => '640w', 'pic_1024.jpg' => '1024w', 'pic_1980.jpg' => '1980w' }, sizes: '100vw', class: 'my-image'
#
# => <img src="/assets/ants_1980.jpg" srcset="/assets/pic_640.jpg 640w, /assets/pic_1024.jpg 1024w, /assets/pic_1980.jpg 1980w" sizes="100vw" class="my-image">
#
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
end
@ixley
Copy link

ixley commented Jun 30, 2015

Anyone using this with Middleman (v3) can swap path_to_image with image_path

@moxie
Copy link

moxie commented Aug 27, 2015

I've taken this a little further https://gist.github.com/moxie/5e99743fbb6e517b1ccf. Still allows specifying srcset as a hash, but does a little checking to determine if the given image path is a local asset path or perhaps a URL. Also adds a little sizes DSL to work with Bootstrap's default breakpoints. Hope it might help someone.

@mjwong
Copy link

mjwong commented Dec 1, 2015

Thanks!

@chavab1
Copy link

chavab1 commented Sep 21, 2016

I keep getting Asset was not declared to be precompiled in production.
I changed path_to_image to image_path and also tried asset_path but I keep getting the same results.

Any suggestions??

Thanx

@taranda
Copy link

taranda commented Dec 30, 2016

Nice code snippet. Thanks.

@xgotyou
Copy link

xgotyou commented Mar 19, 2018

I prefer using naming convention for 2x retina images (ex. image.png -> image@2x.png), so you don't need to supply srcset for your helper every time. Just use it like this: retina_image 'image.png'. Simple. Here is the gist of the helper method.

@horatiorosa
Copy link

This is still a useful snippet. Thanks 👍

@murdoch
Copy link

murdoch commented Oct 5, 2018

@mtribone
Copy link

mtribone commented Nov 3, 2018

@murdoch 🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment