Best way to target a specific page in a collection

Rather than loop through my collection ‘products’ then use a condition to check if it’s the specific page I want… is there a way to to target a specific page?

Here is the page I would like to target in liquid

_collections
  _products
      sample
         index.md

Thanks for your helps

If you can use something from the front matter, that would be ideal. For example, if you have a collection item that looks like this:

---
title: Sample
---
Content to display for the collection item...

You can then create code to display the item with code like this:

<h2>Here is a sample</h2>
{%- assign samples = site.samples | where: 'title', 'Sample' -%}
{% for sample in samples %}
    <p>Title: {{ sample.title }}</p>
{% endfor %}

By assigning the variable first, you can add a where clause and you should get the results you are looking for.

2 Likes

This looks simple enough to implement. Thank you @BillRaymond !

1 Like

where filter

Indeed you need a where clause to get a page. By name, title, whatever.

A for loop is unnecessary if you will get most one result.

{%- assign sample = site.samples | where: 'title', 'Sample' | first-%}

link tag

I would say there is a more appropriate way to get a single page on Jekyll site.

Use the link tag. Pass it the full path to a page, not just the filename. So it is accurate.

If the path is invalid because you made a typo or the page is renamed or moved, you’ll find out when you run Jekyll serve or build. Whereas using where means you might get 0, 1, or even more pages and if you get zero then you’ll deploy a page which is missing section because it could not find the page it was expecting.

Say for an HTML a tag, here are examples

href="{% link index.md %}"

href="{% link team/joe.md %}"

href="{% link _products/appliances/coffee-machine.md %}"

Note that the path is relative to repo root, regardless of the current page.

If using Jekyll 3 then you need a subpath:

href="{{ site.baseurl }}{% link index.md %}"

Also note that your structure is not typical.

_collections
  _products

A collection is usually

_products

And setup in config adds products (no underscore) under collections variable.

Then access a product pages with

site.pages  # all pages. Including posts, plain pages and collections 

site.products # all pages in the products collection 

site.collections  # includes multiple collections 

I have a simple collection demo here as languages. I iterate through pages in the collection.