简体   繁体   中英

How to show first post from category in Jekyll with 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 %}

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'] .

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