Skip to content

Instantly share code, notes, and snippets.

@pzi
Forked from youngbrioche/images_helper.rb
Last active August 30, 2018 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pzi/9cb422914809686d1d7d to your computer and use it in GitHub Desktop.
Save pzi/9cb422914809686d1d7d to your computer and use it in GitHub Desktop.
Middleman helper that acts as thin wrapper for the image_tag helper. It generates the srcset attribute for regular image tags.
helpers do
# Acts as a thin wrapper for image_tag and generates a srcset attribute for regular image tags
# for usage with responsive images, supports middleman's asset_path helper.
#
# 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| "#{asset_path(:images, src)} #{size}" }.join(', ')
image_tag(source, options.merge(srcset: srcset))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment