An elegant way to get a Jekyll collection item by name?

In Jekyll 2.5.3, I use albums

collection (because I need not only the data, but also the generated pages).

When using Jekyll Data Files , you can get data for a specific item as simple as:site.data.albums[foo]

But with collections, things are much worse. All these ways I've tried just don't do anything:

  • site.albums[foo]

  • site.collections.albums[foo]

  • site.collections.albums.docs[foo]

  • site.collections.albums.files[foo]

Therefore I need:

  • Scrolling through all items in the collection
  • For each of them get a naked name
  • Compare this name with some target name
  • If the name is the same, finally assign the data of the collection item to some variable to use

Any better suggestions?

+3


source to share


2 answers


I just did this today, you are correct with your statements. This is how I did it:

<!-- this is in a partial with a 'name' parameter -->
{% for item in site.albums %}
    {% assign name = item.path | split:"/" | last | split:"." | first %}
    {% if name == include.name %}
        {% assign collectionItem = item %}
    {% endif %}
{% endfor %}

      

Using



{{ collectionItem.title }}
{{ collectionItem.url }}
{{ collectionItem.path }}

      

It can even be used to fill in values ​​in other particles, for example:

{% include card.html title=workItem.title bg=workItem.card.bg href=workItem.url %}

      

+2


source


Starting in Jekyll 3.2 , you can use a filter where_exp

to filter a collection based on any of its properties. Therefore, if I have the following item in the collection albums

:

---
title: My Amazing Album
---
...

      

I can grab the first match of an element using this name:

{% assign album = site.albums 
    | where_exp:"album", "album.title == 'My Amazing Album'" 
    | first %}

      



Note that I am using a filter first

because it where_exp

returns an array of matched items.

And then use it in any way:

<h1>{{ album.title }}</h1>

      

I can't vouch for the build performance of this method, but I must present it better than a Liquid loop.

+2


source







All Articles