Code snippet: sidebar menu

Here’s a simple code snippet that uses the awesome macro feature in Twig, it’s also Bootstrap friendly. Enjoy!

{% macro loop(page, parent_url) %}
  {% for p in page.children %}
     {% if p.visible %}
       {% set active_class = (p.active or p.activeChild and (parent_url != p.url)) ? ' active' : '' %}
           {% if p.parent().url == parent_url or p.url == parent_url %}
              <a class="list-group-item{{ active_class }}" href="{{ p.url }}">{{ p.menu }}</a>
            {% endif %}
            {{ _self.loop(p,parent_url) }}
          {% endif %}
    {% endfor %}
{% endmacro %}

<div class="list-group">
  {{ _self.loop(pages, page.parent().url) }}	
</div>
---

Thanks for the snippet but what is different between this and the ‘cookbook’ entry we have on the learn site?

dropdown-menu cookbook entry

It passes the parent url to allow filtering of child pages related to the parent page, therefore providing more granular control with implementing a context based sidebar menu where you may not want to see the entire pages tree.

Ah neat! I didn’t see that in there. Thanks for sharing!

thanks a lot! does anyone know how to get li.active in such a submenu when a top level menu entry is just a redirect to one of the subsequent second level entries? i am everything but familiar with php/twig. help would be appreciated very much!

If you look in the templates/partials/navigation.html.twig file you will see this already implemented.