TIL Hugo can figure out image dimensions at build time
I’d been hardcoding width and height attributes in my Hugo templates to prevent layout shift. It worked fine, but it was tedious — every time I changed an image, I had to look up the new dimensions and update the template by hand.
Today, I had to add a new image to the sidebar, and I felt lazy enough to ask copilot to find the dimensions for me and
insert them into the template. It instead did something unexpected. It used an odd new Hugo function called
imageConfig instead.
Curious, I looked it up. I haven’t kept myself up to date with Hugo’s latest features the last few years. The embarrassing part is that, as it turns out, this isn’t a new function. It was added in 2017 (!), but I hadn’t heard of it until now. I had no idea that Hugo could discover image dimensions at build time. Seems I really should read up more about what all Hugo can do.
Anyway, I found out that it is part of what Hugo calls “Hugo Pipes” — an asset processing pipeline that allows you to do a lot of things with your assets at build time.
It needs me to move my images from the static/ directory to the assets/ directory. And then I can use
resources.Get (even imageConfig is considered
to be legacy) at build time, discover the dimensions of the image, and get the URL via .RelPermalink.
So earlier, I had to do this in my template:
<img src="/images/kagi-small-web.png" width="202" height="64"
alt="Small Web seal">
Now, I can do this:
{{ with resources.Get "images/kagi-small-web.png" }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}"
alt="Small Web seal">
{{ end }}