Search code examples
jekyllliquidyaml-front-matterprose

Is there a way to loop through the front matter of a jekyll collection?


I have a Jekyll collection which is not being output, but elements of which are being displayed on a single page, like this:

{% for element in site.collection %}
  {{ element.content }}
{% endfor %}

I would like to be able to do something like this:

{% for element in site.collection %}
  {{ element.content }}
  {% for front_matter in element %}
    <!-- do stuff -->
  {% endfor %}
{% endfor %}

This is possible with YAML hashes in YAML _data files, but doesn't work here because, it seems {{ element }} on its own is identical to {{ element.content }}. There doesn't seem to be any variable designated for this either like, {{ element.front_matter }}. Is it possible to loop through the front matter of an element in a jekyll collection?

I know that the ideal way to do this would be to include all the front_matter I want to loop through in a variable, like:

---
front_matter:
  foo: bar
  bar: foo
---

But, as I'm trying to configure these pairings (foo and bar) to be easily updatable through prose.io, they can't be nested under other values. If there is a way around this with prose though, I would accept that answer.

Much appreciated!


Solution

  • It is possible to loop through the variables of an element in a Jekyll collection:

    {% for items in site.my_collection %}
      {% for item in items %}
        {{ item }}: {{ items[item] }}
      {% endfor %}
    {% endfor %}
    

    But it is important to remember that there is other metadata that is also available and will be included in the iteration, like path, url, etc and your front matter, e.g. for _my_collection/something.md:

    next:
    
    path: _my_collection/something.md
    
    output: <p></p>
    
    url: /my_collection/something.html
    
    id: /my_collection/something
    
    content: <p></p>
    
    collection: my_collection
    
    relative_path: _my_collection/something.md
    
    excerpt: <p></p>
    
    previous:
    
    draft: false
    
    categories:
    
    slug: something
    
    ext: .md
    
    tags:
    
    date: 2017-05-23 14:43:57 -0300