Generating a unique number or string

My shortcodes often need unique identifiers for scripting and WAI-ARIA purposes. I have cheated by base64ing the {{.Inner}} and appending it like id="thing-{{ $uniq }}".

I’m assuming there’s a better / standard way?

Many thanks.

1 Like
{{ now.UnixNano }}

Is probably the closest … You also have the related shuffle func.

1 Like

Thank you, @bep. I’ll work with that. Was looking at shuffle, but since this is a small, one-line shortcode UnixNano seems like a good fit.

Hashing something, e.g. .Inner, with either md5, sha1 or sha256 could work as well. But now.UnixNano might more performant.

I was using those before, yeah, but they only work if each instance has different content. Which is likely but not 100% dependable.

Warning: if called multiple times in a single page, this will return the same value each time.

Here’s what I used:

{{ $id := delimit (shuffle (seq 1 9)) "" }}
3 Likes