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

Other Articles

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.

List of Most of File Type extension for drupal File field

List of Most of File Type extension for drupal File field : 

Creating a Self-Signed SSL Certificate linux/centos

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

Drupal 8 Theming Essential Guide

What's new? I’ll list some changes with the theming system of Drupal 8 compared to Drupal 7. You may have got familiar with these in the Drupal 7 version.

Import Database using xampp mysql command prompt windows

As we all know the xampp is most popular tool at machine level programming work, but sometime we need to deal with the bigger databases to import into mysql of xampp that provide and we import that

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,

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.

How to Install Civicrm into Drupal 7

There is a direct guide available on CiviCRM Website, Here we follow faster steps to do the same.

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:

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.

Render menu on page template in custom way Drupal 8

If you want to render the menu items in custom way in page or node twig template of drupal 8 then this article is for you :  

Embed Google maps on website (Static address )

Here using this website  we can get the embed the static map on our 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.

Recursively delete all files of a specific extension

Usually we all use "rm" command to delete or remove the files and folder on linux, but if we want to delete the specific type of content/files then we can use "find" command to find and "delete" co

Menu template in drupal 8 for specific customization

Drupal 8 gives the flexibility to make menu template and design the menu with our need, to do this --

Subtract two angularjs dates

hey, Here you get how to subtract to date in angularjs with core functionality

Fix Bug Phpmyadmin [sql.lib.php] + Php7.2 + Ubuntu 16.04

I have faced this error recently , look like this    Warning in ./libraries/sql.lib.php#601

Drush Installation

Heys, Steps to installing drush using composer on server - login to putty - check the composer is install and working by "composer --version"

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".

Reindex the Array keys

Sometimes we need to slice the array for certain values using program a code and at that time key of array is also unset. If you faced the same then you can use these options

Print array or object in watchdog drupal 8

Similar to drupal 7, Drupal 8 also provide the logging functionality but little different to use it because the drupal 8 is symphony base architecture, so can use the logger service of drupal 8 to

page templates for content types in Drupal 8

If you know how to make a content type template in drupal 7 then you can easily understand in drupal 8, Here there is not much change except that the template is in twig format. 

Recent Posts

[SOLVED] PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

If you get the same error like below in VScode editor then you are the right place to 

Redirect Old Domain to New Domain via .htaccess

Usually we develop the site on developement or subdomain and when we finally mirgate the to new domain then some of thing will remain or page redirect happens in  sometimes , so In this case .htacc

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.