1

There's a Liquid filter sample that allows you to "pick a random value from an array. Optionally, pick multiple values". (See documentation here)

My use case is to have a photo journal for viewers to click and generate one random post from my existing collection "photodiary", and not repeat the post in the next click.

Here's my code:

{% assign posts = site.photodiary | where_exp:"post", "post.url != page.url" | sample: 8 %}
        {% for post in posts limit:1 %}
        <a class="prev" href="{{post.url}}">Load a post</a>
    {% endfor %}

</div>
  <main>
    {%- if page.content-type == "photodiary" -%}
      <h2>{{page.title}}</h2>
      <p>  {{content}} </p>
        {%- endif -%}

  </main>

Currently I only have 8 entries, hence the sample: 8.

While the code works, after 1-2 clicks, the posts will be repeated and my page will only load the same 2 to 3 posts.

Can anyone let me know if there's a flaw in the logic or my code? Thanks much!

LP995
  • 11
  • 1
  • Hello, @LP995, have a look at [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – Miguel May 27 '21 at 10:24

1 Answers1

0

Jekyll is a static site generator. This means that Jekyll generates the site once, so filters are applied only when building the site. The sample filter will randomly choose one or more posts and insert it in your page, but won't change when reloading the page, because the site has already been generated.

The kind of dynamic behavior you want can't be achieved by Jekyll, so you will have to do it other way. Take a look to Generating a random link through Javascript/HTML

Miguel
  • 2,130
  • 1
  • 11
  • 26