Color from a string

I came up with this snippet today, which might be useful to others:

  {{ $title := .Title }}
  {{ $palette := slice "79B473" "70A37F" "41658A" "414073" "4C3957" }}
  {{ $hash := $title | lower | crypto.FNV32a }}
  {{ $index := mod $hash (len $palette) }}
  {{ $color = printf "#%s" (index $palette $index) }}
6 Likes

Nice.

Used with the .Colors image method, this will return a random, dominant color from the image. Unlike the shuffle function, this will return the same color on a given page every time you build the site, because the “random-ness” is based on the page title. Change the page title, and the color may be different.

2 Likes

So, what I like about the above approach is that it will give the same color for the same string, useful if you want to put some colours to your taxonomy terms etc.

2 Likes