Jekyll Show Random Posts
Neither in Jekyll
nor in Liquid
there is a option to get a random value out of an array. But there is modulo
filter which can be used to archive the goal.
I found a solution on StackOverflow - 31490789, and adjusted my need a bit so I was able to get three different random posts.
---
layout: post
title: "Jekyll Show Random Posts"
date: 2021-01-22 12:41:37 +0200
---
{% assign random1 = site.time | date: "%s%N" | modulo: site.posts.size %}
{% assign post_random1 = site.posts[random1] %}
{% assign random2 = site.time | date: "%s%N" | plus: 20 | modulo: site.posts.size %}
{% assign post_random2 = site.posts[random2] %}
{% assign random3 = site.time | date: "%s%N" | plus: 80 | modulo: site.posts.size %}
{% assign post_random3 = site.posts[random3] %}
<ul>
<li><a href="{{ post_random1.url }}">{{ post_random1.title }}</a></li>
<li><a href="{{ post_random2.url }}">{{ post_random2.title }}</a></li>
<li><a href="{{ post_random3.url }}">{{ post_random3.title }}</a></li>
</ul>
The code above can be used in markdown
and html
files inside the pages
, _posts
and _drafts
folder.
The idea behind is to get a bit of randomness by using the current time and then use modulo to keep inside the limits of your post array. To get instead a single random post I have add one time 20
and one time 80
, any number would be fine as well.
This is the example output of three different blog posts, by using the liquid code
Weitere BeitrÀge innerhalb der Kategorie