Created
September 15, 2016 18:30
-
-
Save lucasmazza/bd1574b84648625ea9b0ac50ec74a7f3 to your computer and use it in GitHub Desktop.
Helper method to generate `picture` tags.
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 PictureHelper | |
# Public: Generate a `picture` tag with multiple sources for different formats | |
# (JPG, WEBP, PNG, etc) and with support for high density displays. An `img` | |
# element will also be created, so the User Agent can display it's selected | |
# source and use as a fallback if it doesn't support the `picture` element yet. | |
# | |
# Examples | |
# | |
# # => picture_tag('blankslate', formats: %(webp png)) | |
# This call will return a `picture` element with two `source` children | |
# elements - one for the `blankslate.webp` asset and another for the | |
# `blankslate.png` one. Both `source` will also look up for a | |
# `blankslate-2x.webp` (or `blankslate-2x.png`) image to be set as the high | |
# density alternative. | |
# | |
# source - The path for the image (without extension) inside the | |
# Asset Pipeline. | |
# formats: - An `Array` of image formats that should set as sources for | |
# the picture. | |
# alt: - A `String` with the image's alternative text. | |
# html_options - `Hash` of HTML attributes for the `picture` element. | |
# | |
# Returns the `String` with the `picture` element. | |
def picture_tag(source, formats:, alt: nil, **html_options) | |
nodes = Array(formats).map do |format| | |
default = image_path("#{source}.#{format}") | |
retina = image_path("#{source}-2x.#{format}") | |
tag(:source, srcset: "#{default}, #{retina} 2x", alt: alt, type: "image/#{format}") | |
end | |
nodes << image_tag(image_path("#{source}.#{formats.last}"), alt: alt) | |
content_tag(:picture, safe_join(nodes), html_options) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment