adamb
adamb

Reputation: 427

How to loop through categories in a Jekyll collection

I'm trying to loop through categories that have been added to collection posts. For the default 'posts' section it's as easy as:

{% for category in site.categories %}
    {{ category }}
{% endfor %}

But I can't seem to get this working for my collection. I thought it would be something along the lines of:

{% for category in my_collection.categories %}
    {{ category }}
{% endfor %}

But that doesn't seem to work. Any help would be appreciated.

Upvotes: 4

Views: 2180

Answers (3)

Luca Ricci
Luca Ricci

Reputation: 1

You first have to declare the collection

{%a assign col  = site.COLLECTIONNAME %}

Then you can loop inside the collection

{% for cat in col %}
   {{ col.name }}
{% endfor %}

Upvotes: -2

danyamachine
danyamachine

Reputation: 1908

you can grab the name of each category like so:

{% for category in site.categories %}
   {{ category | first | strip_html }}
{% endfor %}

Upvotes: 1

adamb
adamb

Reputation: 427

for anyone needing the answer to this...I've managed to solve this by adding all unique 'my_collection' categories to an array then looping through that. Here's the code:

<!-- create categories array-->
{% assign categories_array = "" | split:"|" %}

<!--Add each unique 'my_collection' category to the array-->
{% for post in site.my_collection %}
    {% for category in post.categories %}
        {% assign categories_array = categories_array | push: category | uniq %}
    {% endfor %}
{% endfor %}

<!--Output the categories-->
{% for category in categories_array %}
    {{ category }}
{% endfor %}

Upvotes: 3

Related Questions