Generate the @2x img
tag src
and srcset
(see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-srcset) attributes for a given image path, only including a 2x srcset
if it exists on the filesystem.
Listen, I got really tired of pasting this absolute nonsense into my templates all over the place:
{% assign retinaImage = postImage | split: "" | reverse | join: "" | replace_first: '.', '.x2@' | split: "" | reverse | join: "" %}
ugggh
(https://jekyllrb.com/docs/plugins/installation/)
One of two options:
- In your
Gemfile
, add thejekyll_plugins
group if it doesn't already exist, and addjekyll-twoxify
to it. For example:
group :jekyll_plugins do
gem "jekyll-twoxify"
end
- Tell bundler to install any plugins with
$ bundle install
-
In your
_config.yml
, add theplugins
key if it doesn't already exist, and add a value ofjekyll-twoxify
. For example:plugins: - jekyll-twoxify
-
Install this gem
$ gem install jekyll-twoxify
Add the twoxify
template tag to any img
tag in place of both the src
and srcset
attributes, with the desired image path. The tag will output the src
value and, if it exists in the filesystem, the srcset
attribute with the @2x path. It will automagically prepend the site.url
to both paths.
Pass in image as a string:
<img {% twoxify "assets/img/mycoolphoto.jpg" %} />
If [email protected]
exists, results in:
<img
src="https://mycoolwebsite.com/assets/img/mycoolphoto.jpg"
srcset="https://mycoolwebsite.com/assets/img/[email protected] 2x" />
Else:
<img src="https://mycoolwebsite.com/assets/img/mycoolphoto.jpg" />
Variables or frontmatter are also supported:
<img {% twoxify post.image %} />
{% assign copied_image = "/assets/wow/numbertwo.png" %}
<img {% twoxify copied_image %} />