How to create a dynamic menu in Jekyll that auto-populates nav items when creating new pages


#1

I am wondering how to go about creating a dynamic menu in Jekyll that automatically populates the navigation with nav items whenever a new page is created to make it easier for clients to maintain. I read an article -https://thinkshout.com/blog/2014/12/creating-dynamic-menus-in-jekyll/ that touched a bit on the subject, but it was geared toward just sub-nav items. Has anyone had any experience in doing something like this?

Thanks!


#2

You can loop through site.pages or site.posts to populate your nav logic. I believe Jekyll’s default theme Minima does this to list all of the site’s pages in the header.


#3

It is a bad idea to do this automatically. However, it is very easy to achieve. Here is the code:

<ul>
  {% for item in site.pages %}
    <li {% if page.url contains item.url %}class="active"{% endif %}><a href="{{ item.url }}">{{ item.title }}</a></li>
  {% endfor %}
</ul>

Source: https://jekyllcodex.org/without-plugin/simple-menu/

To define the order of appearence, you might want to add a front matter variable called ‘order’ to the pages and add a different pagenumber to this variable on each page. The code should sort the pages before looping over them. That looks like this:

{% assign sitepages = site.pages | sort: order %}
{% for item in site.pages %}
...
{% endfor %}

Happy coding!


#4

Thanks a bunch for help and link. Also, why would it be a bad idea, just curious?

Thanks again!