In Hugo v0.108, I Can Finally Handle Responsive Images This Way
Published: Updated:
I accidentally wrote about this very topic twice, lol. The newer post will redirect to here.
One thing I’ve tried to nail on my Hugo static site is how to handle images properly. “Properly” means many things like responsive images, resolving in feed readers, not clogging up my git repo among others. Thanks to Hugo v0.108, I can specify responsive images in shortcodes.
I could technically do it before, but not in the way I wanted it to. Long story short, I wanted to wrap an <img>
element in a <picture>
tag with some <source>
elements to enable responsive images. The markup in the markdown would look something like this:
{{% picture %}}
{{% source srcset="chicken-tikka-masala.avif" type="image/avif" %}}
{{% source srcset="chicken-tikka-masala.webp" type="image/webp" %}}
![An iPad screen illuminates a dark setting begind a dish of chicken tikka masala, rice, kachumber and some cheesy naan in foil.](chicken-tikka-masala.jpg)
{{% /picture %}}
Note that the picture and source shortcodes enumerate the element’s attributes and the space between the sources and image element is mandatory. All well and good, but Hugo would wrap the image element ![…](…)
in a paragraph tag. As of v0.109 there is an option to disable wrapping standalone images in a paragraph tag by setting this in your config file:
markup:
goldmark:
parser:
wrapStandAloneImageWithinParagraph : false
renderer:
unsafe: true
With this, I can now experiment with responsive images. It’s not my ideal implementation (it won’t show in feed readers unless you use a full url), but it’ll be helpful until I do this properly.
Couldn’t You Do This In HTML?
I could?
Wait, I can!
Actually, never mind.
Were I to write this instead:
<picture>
<source srcset="chicken-tikka-masala.avif" type="image/avif">
<source srcset="chicken-tikka-masala.webp" type="image/webp">
![An iPad screen illuminates a dark setting begind a dish of chicken tikka masala, rice, kachumber and some cheesy naan in foil.](/images/chicken-tikka-masala.jpg)
</picture>
It now wraps the image element in a paragraph tag. I should file a bug.