Alexandru Popovici
Alexandru Popovici

Reputation: 143

Grouping collection by category

I have the following collection in my jekyll project:

portfolio
|- portrait
|-- daniel.md
|-- george.md
|- nature
|-- national-park.md
|- food
|-- lasagna.md
|-- buritto.md
|-- pizza.md

What I want is to render a portfolio page grouping my portfolio by categories [ such as: portrait, nature and food ].

I've only managed to render my portfolio in one flat level like this:

<ul>
  {% assign portfolio = site.portfolio %}
  {% for entry in portfolio %}
  <li class="item">
    <h4 class="post-title">{{ entry.title }}</h4>
  </li>
  {% endfor %}
 </ul>

Upvotes: 1

Views: 206

Answers (1)

Alexandru Popovici
Alexandru Popovici

Reputation: 143

I've found a solution. I've added the category name in front matter for each of the markdown files:

---
category: portrait
---

Then, I've changed my liquid to this:

{% assign category = site.portfolio | group_by: 'category' %}
{% for item in category %}
  <!-- This is the category name -->
  <h2>{{item.name}}</h2>
  <ul>
    <!-- filter the categories, selecting only the current category in the loop -->
    {% assign portfolio = site.portfolio | where: 'category', item.name %} 
    {% for entry in portfolio %}
    <li class="item">
      <h4 class="post-title">{{ entry.title }}</h4>
    </li>
    {% endfor %}
  </ul>
{% endfor %}

Is there any other way not to use front matter but the name of the folders inside my collection?

Upvotes: 1

Related Questions