Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An elegant way to get Jekyll collection item by name?

In Jekyll 2.5.3, I use albums collection (because I need not only data stored, but also pages generated).

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

But with collections, things are much worse. All those ways I've tried just do nothing:

  • site.albums[foo]
  • site.collections.albums[foo]
  • site.collections.albums.docs[foo]
  • site.collections.albums.files[foo]

So I need to:

  1. Loop through all collection items
  2. For each of them get a bare name
  3. Compare this name with some target name
  4. If the name matches, finally assign collection item data to some variable to use

Any better suggestions?

like image 913
thybzi Avatar asked Jun 21 '15 12:06

thybzi


2 Answers

I have just done this today, you are correct with your assertions. Here's 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 %}

Usage

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

It can even be used to populate values in other partials, like so:

{% include card.html title=workItem.title bg=workItem.card.bg href=workItem.url %}
like image 106
Zander Avatar answered Sep 28 '22 09:09

Zander


As of Jekyll 3.2, you can use the filter where_exp to filter a collection by any of its properties. So if I have the following item in an albums collection:

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

I can grab the first match for an item by that name:

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

Note that I use the first filter because where_exp returns an array of matched items.

And then use it any way I like:

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

I can't vouch for the build performance of this method, but I have to imagine it's better than a Liquid loop.

like image 33
Nathan Arthur Avatar answered Sep 28 '22 07:09

Nathan Arthur