HUGO

Generate a random string

I recently fixed an issue where I needed to generate a random string. The string had to be random, even if given the same input seed.

In short, there is a shortcode that creates “expandables” with a little js. Each expandable generates its html id based off the md5 hash of the shortcode’s .Inner content. Well, if two expandables had the same inner content, then things would break. My solution was:

  • Get the md5 hash of the seed string
  • Split that into an array
  • Shuffle the array
  • Convert the array back into a string
{{ $seed := "foo" }}
{{ $random := delimit (shuffle (split (md5 $seed) "" )) "" }}
{{ $random }}

This will generate a new string each time you build the site:

5b16c8cffebcc48ac4d2ad4dcfc54ed8
d45ac5c6ce8c8fdcff8dbdbace44421c
...
7 Likes

you can concat a time string ( now as full date / time string ) to the seed

2 Likes