Last active
February 8, 2024 08:15
-
-
Save youngbrioche/4fc71c8d09646567111f to your computer and use it in GitHub Desktop.
Responsive images helper using srcset in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This is still a useful snippet. Thanks 👍
Rails' image_tag
supports srcset now: https://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag
@murdoch 🥇
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.