Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through categories in a Jekyll collection

Tags:

jekyll

liquid

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.

like image 584
adamb Avatar asked Oct 21 '25 03:10

adamb


2 Answers

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 %}
like image 105
adamb Avatar answered Oct 25 '25 22:10

adamb


you can grab the name of each category like so:

{% for category in site.categories %}
   {{ category | first | strip_html }}
{% endfor %}
like image 21
danyamachine Avatar answered Oct 25 '25 20:10

danyamachine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!