How to index a few selected posts from different collections?

What is the best way to index a selection of posts from different collections?

The goal is to create a home page with a preview of a few pages from unrelated collections.
That is easy to do with posts, using categories or custom variables like here:

{% assign posts = site.posts | where_exp: "post", "post.categories contains 'portfolio'" %}
    {% for post in posts %}

But it doesn’t work with collections the same way.

{% for collection in site.documents %} returns all posts and all collections, no idea how to limit and sort them then.

Thank you!

Iterate over collections

Ignore posts collection

Then get pages in each collection

And add a limit

{% for collection in site.collections %}
    {% unless collection.label == "posts" %}
        {{ collection.label }}
        <ul>
        {%- for c in collection.docs limit 3%}
              <li>
                   <a href="{{ c.url | relative_url }}">
                       {{ c.title }}
                   </a>
              </li>
        {% endfor -%}
        </ul>
    {% endunless%}
{% endfor %}

See my similar code in use here

2 Likes

Thank you very much, Michael.

My revised code, thanks to your example:

{% for collection in site.collections %}
{% unless collection.label == "posts" %}
{{ collection.label }}

{% for collection in collection.docs reversed %}
{{ collection.url | relative_url }} {{ collection.image }} {{ collection.description }} {{ collection.url }} {{ collection.title }}
{% endfor %}
{% endunless %}
{% endfor %}

That sorts and brings all the collections, and not the posts. Perfect!

Now the question becomes, how to sort further through only certain posts in those collections that contain a custom variable, for instance. Now that doesn’t work with the same logic it works with posts.

1 Like

Try this approach

On my site I have a collection called music

And that is albums

And each album are songs and an index.md page for the album

Like your days and months.

So there is no need to tell a day page what month it is in, because the path gives that

For posts you can do this.

It checks if a value exists as a key. It could be true or false or 1 or 0, as long as it is set in the frontmatter the post will show

{% for p in site.posts %}
    {% if p.my_variable %}
        {{ p.name }}
    {% endif %}
{% endfor %}

Check if a value is above a threshold

{% for p in site.posts %}
    {% if p.my_variable and p.my_variable > 4 %}
        {{ p.name }}
    {% endif %}
{% endfor %}