3

I would like to display a randomly chosen post in the front page of my Jekyll site.

Do you have any idea how I could loop and chose a random post each time the page is loaded ?

This is the index that I have at the moment.

---
layout: default
title: Home
---
<h1 class="content-listing-header sans">Posts</h1>

<ul class="content">
{% for post in site.posts %}
  <li class="listing">
    <hr class="slender">
    <a href="{{ post.url }}"><h4 class="contrast">{{ post.title }}</h4></a>
    <span class="smaller">{{ post.date | date: "%B %-d, %Y" }}</span>  <br/>
    <div>{{ post.excerpt }}</div>

  </li>
{% endfor %}

Thanks

giac
  • 4,261
  • 5
  • 30
  • 59

1 Answers1

12

Jekyll generates static files. You can chose a random post to be inserted in your home page, but this page will be static and random post will only be changed when you site is generated.

{% assign random = site.time | date: "%s%N" | modulo: site.posts.size %}
<h1>{{ site.posts[random].title }}</h1>

As liquid has no random tag, you can mimic randomness based on time. See https://stackoverflow.com/a/28323813/1548376

The only way to load a different post on each reload is to do it with javascript. And here it will become complicated.

  • you will need to create a posts list for javascript to choose from,
  • you will have to generate specific page for each post with only post's html in it. No head, navigation and so on. And this can only be accomplished with a Jekyll generator plugin.
Community
  • 1
  • 1
David Jacquel
  • 51,670
  • 6
  • 121
  • 147