Problem:

Sometimes it’s about sending a message. Here the message is that the exact facts don’t matter. To that end I want to inject some randomness into these posts, but only I will know what is true and what is not as. At build time the page should be able to;

  • randomly select dates from a range
  • randomly select words from a list
  • randomly select a time from a range

As the world exists in my mind this website exists in the world. Ever changing and no constants. The next time you look it will be different, or was it always that way?

Solution:

Hugo allows this to happen via “shortcodes”.

Copied below are some of the shortcodes that I’ve implemented for this website. randomdate start="2020-01-01" end="2024-10-10" - 2021-11-10

{{ $startDate := .Get "start" | default "2023-01-01" | time }}
{{ $endDate := .Get "end" | default "2023-12-31" | time }}

{{ $daysRange := div (sub $endDate.Unix $startDate.Unix) 86400 }} 
{{ $randomDays := index (shuffle (seq 0 $daysRange)) 0 }} 

{{ $randomDate := $startDate.AddDate 0 0 $randomDays }}
{{ $randomDate.Format "2006-01-02" }}

randomint min=1995 max=2024 - 2005

{{ $min := .Get "min" | int }}
{{ $max := .Get "max" | int }}

{{ $range := seq $min $max }}
{{ $shuffled := shuffle $range }}

{{ index $shuffled 0 }}

randomword words="a,b,c" - b

{{ $words := .Get "words" }}
{{ $words := split $words "," }}

{{ $shuffled := shuffle $words }}

{{ index $shuffled 0 }}

misc

While writing this up the need to include the content of the shortcode files became apparent. Instead of copying the files manually each and every time they were updated we can use another shortcode do so (courtesy of chatgpt);

include-file file="layouts/shortcodes/include-file.html":

{{- $file := .Get "file" -}}
{{- with readFile $file -}}
{{ . | safeHTML }}
{{- else -}}

Could not read file: {{ $file }}

{{- end -}}