Display sibling pages without using custom front matter variables in Jekyll, based on URL-structure?

Viewed 77

I have a main page for Gotham City, with sub-pages for locations. Each location sometimes also have various types of sub pages. The URLs looks like this:

https://example.com/gotham-city
https://example.com/gotham-city/arkham-asylum <-- Location page
https://example.com/gotham-city/wayne-manor <-- Location page
https://example.com/gotham-city/wayne-enterprises <-- Location page
https://example.com/gotham-city/wayne-enterprise/history
https://example.com/gotham-city/wayne-enterprise/subsidiaries
https://example.com/gotham-city/wayne-enterprise/subsidiaries/wayne-security https://example.com/gotham-city/wayne-enterprise/subsidiaries/wayne-biotech

On each location sub-page, I want to display a list of the other sibling pages (direct children of Gotham City). E.g. on the page Wayne Manor the pages Arkham Asylum and Wayne Manor should be listed.

I want to do this based on the URL-structure, without using front matter variables or any reference to layouts.

Right now I have the follow code in my page layout:

<!-- Split URL into slugs -->
{% assign urlslugs = page.url | remove:'/index.html' | split: '/' %}

<!-- Remove last slug and capture remaining URL as a variable -->
{% capture parentpage %}
{%- for slug in urlslugs offset: 1 -%}
  {%- if forloop.last -%}{%- else -%}{{ slug | replace:'-',' ' | remove:'.html' }}/{%- endif -%}
{%- endfor -%}
{% endcapture %}

<p>Parent page variable test: {{ parentpage }}</p>

<h2>Related pages</h2>

<!-- Loop all pages containing the parent page directory -->
<ul>
{% for sibling in site.pages %}
    {% if sibling.url contains parentpage %}
      {% unless sibling.url == page.url %}
        <li><a href="{{ site.url }}{{ sibling.url }}">{{ sibling.url }}</a></li>
      {% endunless %}
    {% endif %}
{% endfor %}
</ul>

Using this solution, the page for Wayne Manor (https://example.com/gotham-city/wayne-manor) have the following output:

Parent page variable test: gotham-city/

Related pages

  • /gotham-city/arkham-asylum
  • /gotham-city/wayne-enterprise
  • /gotham-city/wayne-enterprise/history
  • /gotham-city/wayne-enterprise/subsidiaries
  • /gotham-city/wayne-enterprise/subsidiaries/wayne-security
  • /gotham-city/wayne-enterprise/subsidiaries/wayne-biotech

Everything works correctly here, except that "History", "Subsidiaries" and "Subsidiaries" sub-pages is displayed, which is unwanted.

Right now I am excluding the current page, but I need a way to exclude the sub-pages of the location-pages.

The way I think this could be solved, is by somehow counting the current "directory level" of the current page with forloop.index, or by counting the number of slashes (/), and compare that to the current URL and exclude all pages with a higher directory depth.

Can this be done only based on URL-structure?

0 Answers
Related