Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Archive

Code snippet: sidebar menu

Started by Muut Archive 12 years ago · 5 replies · 381 views
12 years ago

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

TWIG

{% 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>
---
12 years ago

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.

12 years ago

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

12 years ago

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!

12 years ago

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

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1296 9 years ago
Archive · by Muut Archive, 9 years ago
2 890 9 years ago
Archive · by Muut Archive, 9 years ago
2 4019 9 years ago
Archive · by Muut Archive, 9 years ago
1 2894 9 years ago
Archive · by Muut Archive, 9 years ago
3 1078 9 years ago