I have an image render hook and I want to assign unique ids to each <img>
. I want the ids to be imageName[-index]
where -index
is only present when there are two images on the same page with the same name (e.g. because the image is displayed twice).
Previously this was possible with Page.Scratch
. Something along the lines of
{{ $id := path.BaseName .Destination }}
{{ $images := .Page.Scratch.Get "images" }}
{{ $index := or (index $images $id) 0 }}
{{ .Page.Scratch.SetInMap "images" $id (add $index 1) }}
{{ $suffix := cond $index (printf "-%d" (add $index 1)) "" }}
{{ $id = (printf "%s%s" $id $suffix) | anchorize }}
This worked because Page.Scratch
was reset for each build. But Page.Scratch
has been deprecated and replaced with Page.Store
and that is not reset each build, which causes the ids to change when using hugo serve
How do we implement custom counters associated with pages that reset each build so it produces stable results?
It’s important that ids are stable and aren’t sensitive to unrelated changes on the page. Ids are part of permalinks and should not change unless the author means for them to. This rules out the use of Ordinal
because adding or removing other content to the page will break links.