I am trying to write a shortcode that will accept the name of a Retina-quality (2x) image page resource, and output HTML for the following:
- A scaled version of the image for non-Retina displays, and
- A non-scaled, full resolution version of the image for Retina displays.
It is necessary to know the image’s size ahead of time to do this. I’d like to use imageConfig to do this, but it’s proving challenging since imageConfig
does not accept image resource objects as its argument – it expects paths. How can I obtain the height and width of an image in a Resource?
Here is the solution I’m using today, which kind of works. Given the name of an image resource, it writes the necessary HTML:
{{ $img2x := $.Page.Resources.GetMatch (.Get 0) }}
{{ with (imageConfig (print "content/" $.Page.Dir "/" (.Get 0) ".png" )) }}
{{ $img1x := $img2x.Resize (print (div .Width 2) "x") }}
<img srcset="{{ $img1x.RelPermalink }}, {{ $img2x.RelPermalink }} 2x"
src="{{ $img2x.RelPermalink }}"
width="{{ (div .Width 2) }}"
alt="{{ $img2x.Title }}"/>
{{ end }}
While it works in my use case, this feels hacky because it makes a lot of assumptions about where the image lives and what its extension is. It also requires the image resource’s name to be the same as its filename, which feels wrong.
Is there a more elegant way to do this? Maybe some way to pass the resource’s Content directly to imageConfig
, or a way to expose the resource’s file path?