Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show first post from category in Jekyll with Liquid

Tags:

jekyll

liquid

I can't find a solution. I have three categories: tuts, news, code.

The newest post is categorized in tuts. But I want to show the last and newest post in news. I tried the following, but obviously it doesn't show anything, because if I limit the loop to the first item, which is the tuts item, the loop stops.

{% for post in site.posts limit:1 %}
    {% if post.categories contains 'news' %}
        <a href="{{ site.url }}/news/">NEWS</a></strong> › <a href="{{ site.url }}{{ post.url }}">{{ post.title }}</a>
    {% endif %}
{% endfor %}

How do I show the first posting from a special category? Can I loop directly through a chosen category like this? If yes, what is the correct syntax?

{% for post in site.posts.categories.news limit:1 %}
        <a href="{{ site.url }}/news/">NEWS</a></strong> › <a href="{{ site.url }}{{ post.url }}">{{ post.title }}</a>
{% endfor %}
like image 319
Phlow Avatar asked Jan 10 '23 05:01

Phlow


1 Answers

Yes, it's possible to directly loop all posts for a certain category or tag.

It's just:

  {% for post in site.categories['news'] limit:1 %}
    <a href="{{ post.url }}">{{ post.title }}</a>
  {% endfor %}

It's the same for tags, you just have to replace site.categories['news'] by site.tags['news'].

like image 132
Christian Specht Avatar answered Mar 07 '23 00:03

Christian Specht