0
votes

We are using four different post categories (developers, news, services and careers) in our project and I know how to print all the posts at the same time:

{% for post in site.posts %}
  <li>{{ post.title }}</li>
{% endfor %}

or all posts for each individual category separately:

{% for post in site.categories.news %}
  <li>{{ post.title }}</li>
{% endfor %}

What I’m struggling with is to print only posts from two categories (developers and news) in the same for loop.

This is our folder structure:

_posts/

  • blog/
    • developers/
    • news/
  • services/
  • careers/

The post file looks as following (2017-03-16_my_post.md):

---
title: "Dev post Title"
categories: developers
layout: developer
---

I tried something like this, but I guess you can’t add two arguments to a for loop as this is not working. It only prints posts for the first argument and ignores completely the second one:

{% for post in site.categories.developers and site.categories.news %}
    <li>{{ post.title }}</li>
{% endfor %}

Any ideas how to approach this? I couldn’t find any solution that would work. Any help would be very appreciated! many thanks!

2

2 Answers

1
votes

To filter posts that contains two categories you need to browse all posts and use the "if" operator with "and": condition A and condition B.

{% for post in site.posts %}
{% if post.categories contains "developer" and post.categories contains "news" %}
 <li>{{ post.title }}</li> 
{% endif %}
{% endfor %}

Then it will show only the posts with the categories developer and newsstrong text.

-1
votes

after few hours trying to work this out and loosing my patience I finally got it right.. This loop combined with if statement will print only posts from those two categories:

{% for post in site.posts %}
    {% if post.categories contains 'news' or post.categories contains 'developers' %}
        <li>{{ post.title }}</li>
    {% endif %}
{% endfor %}

Hope it saves someone else a time :)