Your sites Log in Sign up Menu

Show a random post?

Along with {{#previous}}{{/previous}} and {{#next}}{{/next}}, is there a way to show a random post / entry from the blog?


3 years ago, 1 replies   Improve this question

There is no way to retrieve a post at random using the template engine. However, you can spit out all of your entries, or perhaps your recent entries, and use some JavaScript to select one to show at random. Here's a brief illustration of a possible technique to accomplish this using JavaScript:


<h2>Random entry</h2>

<!-- First generate a list of your recent entries -->
<section class="random-entries">
  {{#recentEntries}}
    <a href="{{{url}}}">{{title}}</a>
  {{/recentEntries}}
</section>

<!-- Then we hide all of those entries by default -->
<style type="text/css">
  .random-entries > * {
    display: none
  }
</style>

<!-- Finally we show one entry at random -->
<script type="text/javascript">
  let numberOfEntries = document.querySelector('.random-entries').childElementCount;

  // Generate a random number between 1 and the number of entries
  let random = Math.floor(1 + Math.random() * numberOfEntries);

  // Show the entry with the same index as the random number
  document.querySelector('.random-entries>*:nth-child(' + random + 
  ')').style.display = 'block';

</script>

Source: some of the script was taken from this answer on Stack Overflow.

Answered 3 years ago ยท Improve this answer

Privacy Terms