c0debabe creates

Twig Menus

· Web Development, Twig, Breakdown

Twig templates are flexible and powerful. I go over how to create submenus.

In this specific example I am working in cecil.app; however, many website frameworks use very similar structures so the ideas presented here should be applicable elsewhere.

The basic flow for printing a menu is "for each item in the menu, print a link with the url and the title", which would probably print every page available in the menu system, depending how it's set up.

Usually, there will be a data structure that has all the pages represented in it which you would iterate through with that for loop. In cecil.app, it's a variable called site.pages.showable.

If we want to print a menu just for the current subsection, you would print "for each item in the menu, if the item's url is the same as the current page url then print a link with the url and title".

Even better is if you can mark the current page in the menu and not make it an active link.

So what does this look like in code? Here's what I'm using, commented heavily to help you walk through it.

<!-- start a nav menu -->
    <nav class="me-md-3">
<!-- style the list for the nav (ul) -->
      <ul class="list-group list-group-flush">
<!-- for each subpage in all visible pages, sorted by page weight -->
{%- for subpage in site.pages.showable|sort_by_weight ~%}
<!-- if current page id is equal to the section the current page is in -->
  {% if page.section in subpage.id %}
<!-- then we're printing a navigation item (li) -->
        <li class="list-group-item">
<!-- if this page in the menu is the current page -->
          {% if url(page) == url(subpage) %}
<!-- then we're printing it as an inactive link -->
          <a aria-current="page">{{ subpage.title }}</a>
<!-- else we're printing it as a regular link -->
          {% else %}
<!-- the regular link will use the menu page url and the menu page title -->
          <a href="{{ url(subpage) }}">{{ subpage.title }}</a>
<!-- end if for checking if it's the current page
          {% endif %}
<!-- close the tag for the navigation item (li)
<!-- end if that matches for the section; no else is required -->
  {% endif %}
<!-- close the for loop of each visible page -->
{%- endfor ~%}
<!-- close the list for the nav (ul) -->
<!-- close the tag for the nav itself -->