Skip to content

Instantly share code, notes, and snippets.

@mortendk
Created August 5, 2015 22:21
Show Gist options
  • Save mortendk/ea7dfb70baa0afb3cd18 to your computer and use it in GitHub Desktop.
Save mortendk/ea7dfb70baa0afb3cd18 to your computer and use it in GitHub Desktop.
menu with first, last & count classes in twig Drupal8 template
{#
/**
* @file
* Theme override to display a menu.
*
* Available variables:
* - menu_name: The machine name of the menu.
* - items: A nested list of menu items. Each menu item contains:
* - attributes: HTML attributes for the menu item.
* - below: The menu item child items.
* - title: The menu link title.
* - url: The menu link url, instance of \Drupal\Core\Url
* - localized_options: Menu link localized options.
*/
#}
{% import _self as menus %}
{#
We call a macro which calls itself to render the full tree.
@see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
{% import _self as menus %}
{% if items %}
{% if menu_level == 0 %}
<ul{{ attributes.addClass('menu') }}>
{% else %}
<ul>
{% endif %}
{% for item in items %}
{# by the magic of loop #}
{% if loop.first %}
<li{{ item.attributes.addClass('first') }}>
{% elseif loop.last %}
<li{{ item.attributes.addClass('last') }}>
{% elseif loop.index == "2" %}
<li{{ item.attributes.addClass('two') }}>
{{ loop.index0 }}
{% elseif loop.revindex == "2" %}
<li{{ item.attributes.addClass('two-left') }}>
{% else %}
<li{{ item.attributes }}>
{{ item.attributes }}
{% endif %}
{{ link(item.title, item.url) }}
{% if item.below %}
{{ menus.menu_links(item.below, attributes, menu_level + 1) }}
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% endmacro %}
@mortendk
Copy link
Author

mortendk commented Aug 5, 2015

and yes this is an example for people that dont wanna use
li:first-child{ ... }
li:last-child{ ... }
li:nth-child(4n){...}

@penskyc
Copy link

penskyc commented Jan 14, 2017

How do I add a different class to the dropdown menu than the main ul

@dbjpanda
Copy link

@penskyc Did you implement another class to drop down/ child menu ?

@newtone
Copy link

newtone commented Feb 15, 2022

@penskyc @mortendk I'm also stuck with dropdown capability. Perhaps there is a simple solution?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment