Sauce McBoss
Sauce McBoss

Reputation: 6967

How to access metadata when using "where" filter

I've got a structured set of pages in a collection, and the structure looks something like this:

chapter1
   section1
   section2
   section3
chapter2
   section1
   section2
   section3
chapter3
   section1
   section2
   section3

Each is a separate page that renders its own permalink.

Say I'd like to make a link to chapter3/section1, how would I do this? I'd like to use the Liquid where filter, but this seems to give me the page contents, not the metadata.

{% assign section_post = site.chapters | where:"url","chapter3/section1" %}
{{ section_post }}

This gets me the proper page, but not the right content. If I were to write this in my layout, I get nothing:

<a href="{{ section_post.permalink }}">{{ section_post.title }}</a>

What am I doing wrong? How can I get the metadata using a where filter? I've got a bunch of pages, so looping through them is super inefficient...

Upvotes: 1

Views: 116

Answers (1)

marcanuy
marcanuy

Reputation: 23982

The problem is that a where expression returns all the objects in an array given a certain condition.

[#<Jekyll::Document _chapters/chapter3/section1 collection=chapters>] 

In this case you are expecting that this list of objects just return a single item, so we can select that item with the first liquid tag (returns the first element of an array).

  {% assign ch3s1 = site.chapters |
  where:"id","/chapters/chapter3/section1" | first%} 

  title: {{ch3s1.title}} 
  <br>
  url: {{ch3s1.url}}

would output the desired section:

  title: Chapter 3 section 1
  url: /chapters/chapter3/section1

Upvotes: 1

Related Questions