drupal 8

In Drupal 8 Twig templates give extra power to drupal to add dynamic content in twig style, In this tutorial we can see how we can add the custom menu classes to menu ul li using menu.html.twig.

If you are creating your own theme or custom theme in drupal 8 then to overwrite the menu class we need to override the menu.html.twig template to our theme directory, so copy menu.html.twig form drupal core template to our theme directory

Core template path: [drupal_root]/core/modules/system/templates/menu.html.twig

Core template look like below, now our target is add add custom classes to ul and li - so follow the steps below --

{#
/**
 * @file
 * Default theme implementation 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.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 *
 * @ingroup themeable
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see https://twig.symfony.com/doc/1.x/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 }}>
    {% else %}
      <ul>
    {% endif %}
    {% for item in items %}
      <li{{ item.attributes }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Add custom class without menu name

1) adding set class variable like this

{% 
    set menu_classes_ul = [ 
      'navbar-nav', 
    ] 
  %} 
  {% 
    set menu_classes_li = [ 
      'nav-item', 
    ] 
  %}

So our template will look like this -

{#
/**
 * @file
 * Default theme implementation 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.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 *
 * @ingroup themeable
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see https://twig.symfony.com/doc/1.x/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% 
    set menu_classes_ul = [ 
      'navbar-nav', 
    ] 
  %} 
  {% 
    set menu_classes_li = [ 
      'nav-item', 
    ] 
  %}
  {% if items %}
    {% if menu_level == 0 %}
    {{ attributes }}
      <ul{{ attributes.addClass(menu_classes_ul) }}>
    {% else %}
      <ul>
    {% endif %}
    {% for item in items %}
      <li{{ item.attributes.addClass(menu_classes_li) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Now clear all cache of drupal and see the classes are added

2) Add class with menu_name 

As mention in template "available variables":
 * - menu_name: The machine name of the menu.

we can also add the menu name to class for this you need to add the menu_name at two place:

First:

{{ menus.menu_links(items, attributes, 0) }}

like this 

{{ menus.menu_links(items, attributes, 0, menu_name) }}

Second:

{% macro menu_links(items, attributes, menu_level) %}

like this

{% macro menu_links(items, attributes, menu_level, menu_name) %}

 So you whole template looks like this -

{#
/**
 * @file
 * Default theme implementation 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.
 *   - is_expanded: TRUE if the link has visible children within the current
 *     menu tree.
 *   - is_collapsed: TRUE if the link has children within the current menu tree
 *     that are not currently visible.
 *   - in_active_trail: TRUE if the link is in the active trail.
 *
 * @ingroup themeable
 */
#}
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see https://twig.symfony.com/doc/1.x/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0, menu_name) }}

{% macro menu_links(items, attributes, menu_level, menu_name) %}
  {% import _self as menus %}
  {% 
    set menu_classes_ul = [ 
      'navbar-nav', 'custom-menu-' ~ menu_name|clean_class, 
    ] 
  %} 
  {% 
    set menu_classes_li = [ 
      'nav-item', 'custom-menu-' ~ menu_name|clean_class, 
    ] 
  %}
  {% if items %}
    {% if menu_level == 0 %}
    {{ attributes }}
      <ul{{ attributes.addClass(menu_classes_ul) }}>
    {% else %}
      <ul>
    {% endif %}
    {% for item in items %}
      <li{{ item.attributes.addClass(menu_classes_li) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Clear the cache and you are done.

In other templates we can add the class in same kind, hope this helps and comment below to any queries

Thanks


Please Comment your thoughts and feedback below and add something if you found good in anywhere to help others

Hit a like Button If you like the Post.

Many Thanks

Add new comment

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Other Articles

Create a Flag link programmatically and render flag link in twig template drupal 8

This article is refer to generate the flag link programmatically and render in drupal 8 twig template, before in drupal 7 its was quiet easy to render or generate flag link in just a single line of

Update Drupal 8 core manually

This is small tutorial to how to update the Drupal 8 core manually using shell or FTP, Let start -

Creating a Self-Signed SSL Certificate linux/centos

Self Signed certificates are those are signed by the same individual whose identity it certifies.

Allow Less Secure App Yahoo Mail

hey,  If you want to read email form script you need to allow less secure app as same as Gmail,  Just Go to the link, after login and allow less secure app at the bottom.

Drupal 8 correct a word by default browser auto correct options on textarea field causing by CKEditor

If you are facing the problem to to correct the word in drupal 8 text because of copy and paste default popup on right, we have a simple trick to get over it 

Install JAVA 8 on Ubuntu 18.04/16.04

Install java on Ubuntu 1)Install Oracle Java 8 

Subscribe to Mailchimp programmatically via api with PHP

In this tutorial we can see how to subscribe to the mailchimp subscribe list using php programmatically via api, For this you need a mailchimp account, api key and list id 

Print array or object in watchdog drupal 7

hey, For many purpose we have to print the array or object while making a custom modules or debuging any old module, we have to print the array or object to see the values are fine or not, drupal p

Create Node drupal 8 programmatically with image upload using custom module

As we know drupal 8 use symphony, so module structure of drupal 8 is change and workflow functionality of doing thing also change.

Slice array Elements using Keys PHP

Many Helpful Function are available to exact the specific set of keys of an array $sliced-arr = array_slice($new_tags, 0, 6);

Nodejs With Xampp

Hello Guys, We can easily connect the Nodejs with xampp by follow simple steps -

Send Email using smtp module with Gmail

Here is the link that helps to configure stmp module with Gmail configuration and enables drupal

Flexslider Arrows Changed by arrow Images

Flexslider uses the arrows of its own flexslider family icons, if you want to change or replace with yours images you can do using following css.  

List of all countries

Here is the GitHub Link that helps me to get the list of countries at once May it helps to you also 

Install Apache Solr on Ubuntu

Install Apache Solr 7.7 on Ubuntu 18.04 & 16.04 LTS This tutorials explains how to install solr 7 on ubuntu system 1) Install or Check Java

Render a drupal node d8 twig template

Render a Drupal node in drupal 8 twig template and module PHP code is a bit different from Drupal 7 because Drupal 8 uses Symfony and twig format, follow the step and you will available to render a

WAI-ARIA Roles

See Details Here https://www.drupal.org/node/1179668

Test payment Card Numbers For online payment

This article is for developers who develop eCommerce or payment gateway system for apps and website.

Wordpress Revolution Slider error after upgrade to php 7

A recently got the error below after updating wordpress website to php 7, error causing the website blank and when the debug mode on we got this error, caused by revolution slider.

Scroll to top button with html and jquery

Are you searching to add a button scroll to top, then this article is for you.

Check the size of folder, files and directories using SSH

Following commands(In Bold) used for different purpose  1. Use df -h For check out the used space, free space and total space From all the partitions.

Drupal 8 Opcache Problem with xampp

;Put this code in php.ini (C:\xampp\php\php.ini) zend_extension=php_opcache.dll [opcache] ; Determines if Zend OPCache is enabled opcache.enable=1 ; Determines if Zend OPCach

Getting permission error when installing CiviCRM under Drupal with Xampp

If you are getting permission error while installing CiviCRM on xampp then, its is default CiviCRM user permission error,

Recent Posts

Create a Flag link programmatically and render flag link in twig template drupal 8

This article is refer to generate the flag link programmatically and render in drupal 8 twig template, before in drupal 7 its was quiet easy to render or generate flag link in just a single line of

Jquery prevent enter to submit form

If you want to prevent the form submit using jquery, then this page helps you to doing this.

Code:

Play Pause HTML5 Video using Jquery

HTML5 video playing on any web page is very easy, in this tutorial we can show you how to add video on html and make it play and pause without using html controls.

Import and Export Drupal 8 Views, Or Import and Export any configuration Drupal 8

Import and Export configuration is the basic protocol to staging the website or production website deployment, In Drupal 7, we need the extra modules to import and export or we can use features mod

How to override different version of Jquery in Drupal 8 using theme

Drupal 8 use its own jquery version by default and if you want to use the other version of jQuery instead of default than this tutorials steps is for you, sometimes we need different version to oth

Subscribe to Mailchimp programmatically via api with PHP

In this tutorial we can see how to subscribe to the mailchimp subscribe list using php programmatically via api,

For this you need a mailchimp account, api key and list id 

How you can get Mailchimp API KEY

By Follow steps below, you can find the api key or create the api key at mailchimp and use it to your website to connected the site with mailchimp to collect the subscribe in fastest way.

How to get your MailChimp LIST ID

Mailchimp is marketing automation platform and is provide email for marketing your product or business whatever you like, today its most trusted service providing all over the globe.

How to create the directories and sub directories in one command linux

Many times we are want to create multiple directories and sub-directories under it and usually we do cd and mkdir one by one, it is very time consuming and it sometimes slow down our workflow.

Create Node drupal 8 programmatically with image upload using custom module

As we know drupal 8 use symphony, so module structure of drupal 8 is change and workflow functionality of doing thing also change.

Uncaught TypeError: CKEDITOR.tools.object.keys is not a function

Intergation of code snippet with ckeditor, cause this error "Uncaught TypeError: CKEDITOR.tools.object.keys is not a function".