Categories
Tech

Jekyll: How to auto-generate hierarchical menu

Jekyll, the wonderful static sites generator that new Taragana corporate site is built upon, provides a navigation menu (in the default theme) which is essentially a list of all pages on the sites. This does not work well for sites with large number of pages, corporate sites and especially sites with deep page hierarchy.

Jekyll provide 10 recipes for hierarchical navigation. However, none addresses a very simple need. I have a site, currently, with 3 levels (could be more in future) of hierarchy. In each level I want to have navigation menu show only the children, and one level deep only, in navigation menu so it creates a silo. For example, when I am in Services, I want to show relevant link only for services. The user can at any time go to the Home page by clicking on the logo.

I initially thought of providing a link to the parent, from each page, but decided against it as that would duplicate the function of the back button, which users are very familiar with.

The following code is for the default minima theme. You can replace the entire div class trigger with the following content.

        <div class="trigger">
        {% assign url_parts_size = page.url | split: '/' | size | plus: 1 %}
        {% if page.url == '/' %}
          {% assign url_parts_size = url_parts_size | plus: 1 %}
        {% endif %}
        {% assign mypage = page.url | split: '.html' | first %}
        {% for node in site.pages %}
          {% if node.url contains mypage and node.url != page.url %}
            {% assign node_url_parts_size = node.url | split: '/' | size %}
            {% if node_url_parts_size == url_parts_size %}
              <a class="page-link" href="{{ node.url | split: '.html' | first | relative_url }}">{{ node.title | escape }}</a>
            {% endif %}
          {% endif %}
        {% endfor %}
        </div>

Writing code in liquid is a royal pain due to unconventional syntax. The above code finds out url’s which share the same base path but one level higher (children).

Let me know if you decide to use the above code and what modifications, if any you made.