Random quote from csv

Hello Community!
I’m totally a hugo noob, and i have this question:
I want to display just a random quote on the front page.
It would be the easiest (for me), if these are taken out of a csv file.

Any ideas how i can realize this with hugo?

Thanks for your help!

Hello @leberkas,

first of all we have to access the data in your csv file by reading it. Take a look a the getCSV template func. In the next step we need to get a random quote.

Save your csv file in the data folder and change that path in the example below if necessary.

Et voilà:

<!-- load data-->
{{ $quotes := getCSV ";" "data/quotes.csv" }}
<!-- generate random number -->
{{ $random := mod .Now.Second (len $quotes) }}

<!-- output a random quote from your csv file-->
{{ index $quotes $random }}

The upcoming release of Hugo has a new template func called shuffle. This makes our custom “random number generator” obsolete.

{{ $quotes | shuffle | first 1 }}

Oooh. I like the sound of that!

thanks @digitalcraftsman

ok, i’m really clueless.
i tried your code in a post and in a layout.

But both time i just get the code as content of the page displayed.

What’s wrong?
the csv file was wrong - works now :slight_smile:

Very nice piece of information there. Thanks

Thanks for this. I couldn’t find a shuffle example in the docs, and your code snippet helped me.

For others looking for shuffle examples, this is how I use it:

{{ range (where .Site.Pages "Section" .Section) | shuffle | first 6 }}
  <li><a href="{{ .Permalink }}" title="{{ .Title }}">{{ .Title }}</a></li>          
{{ end }}

(Returns a list of 6 random posts from the same section as the post that’s currently shown.)

Hi, thanks for the code. But I can not get the random thing work on refresh. It got changed only by rebuilding the hugo project. Is it right? And how can I get a random content on refresh?

Hey @foodtooth,

Hugo is a static page generator. It will indeed only shuffle things on a rebuild.
Doing stuff on refreshing the website requires adding javascript to the mix. :slight_smile: