Generating unique ids with a counter

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.

Since you are only adding the ID when there’s a duplicate image, would you be willing to add the ID manually via a query string parameter?

It’s a sensible idea, though I’m not a fan of solutions where I can forget a manual step and have things break in a subtle way. In this case links would end up pointing to the wrong object and focus handling for my lightbox would end moving to the wrong object. Easy to overlook, unfortunately.

My current hack is to reset the page store manually at the bottom of the base layout template.

{{- .Page.Store.Set "images" dict }}