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

Viewed 223

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. I read an article 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!

1 Answers

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!

Related