Searching for page in site.pages by path without iteration

Viewed 38

I have a path to some page from root in Jekyll as a variable path. I want to get some variables from FrontMatter of that page. How could I find this page in site.pages without iterating over all pages? I mean something like

{% assign aim = site.pages[path] %}

instead of

{% for p in site.pages %}
  {% if p.path == path %}
    {% assign aim = p %}
  {% endif %}
{% endfor %}

Will this solution be faster for a site with a thousand of pages?

2 Answers

You can use the where liquid filter for this:

{% assign aim = site.pages | where:"path",path %}

Thanks @β.εηοιτ.βε for the hint!

That was what I expected, but when I used this template, I've faced the problem: the output of {{aim.title}} was empty.

The where filter produces list even it consists of just one element! But each filepath in a file system points exactly at one file, so I expected that aim will be the page, not a list. To fix this, I've added first filter:

{% assign aim = site.pages | where:"path",path | first %}

And now aim is the page variable I am searching for.

About speed. This solution builds a site 2X faster on my hardware.

Related