简体   繁体   中英

How to use Liquid "sample" filter to generate a random post in Jekyll?

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM