Generate a Random String in Hugo

Published: Jun 17, 2020
Updated: May 3, 2021

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, the cupper theme (which had the issue) has a shortcode that creates “expandables” with a little JavaScript. Each expandable generates its html id based off the md5 hash of the shortcode’s .Inner content (which is whatever text you want to show when the expandable is clicked). Well, if two expandables had the same inner content, then things would break. My solution was:

{{ $seed := "foo" }}
{{ $random := delimit (shuffle (split (md5 $seed) "" )) "" }}
{{ $random }}

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