Drupal 8 twig

Instead of creating blocks for each and every menu you want, it ould be easier to directly print your custom menus in a twig template of single block as if it was a variable made available to the twig.

Twig is a modern template engine for PHP

  • Fast: Twig compiles templates down to plain optimized PHP code. The overhead compared to regular PHP code was reduced to the very minimum.
  • Secure: Twig has a sandbox mode to evaluate untrusted template code. This allows Twig to be used as a template language for applications where users may modify the template design.
  • Flexible: Twig is powered by a flexible lexer and parser. This allows the developer to define its own custom tags and filters, and create its own DSL.

In order to achieve this the code below should in the following path :

modules/your_module/src/Twig/RenderMenuExtension.php

<?php
namespace Drupal\custom_module\Twig;

class RenderMenuExtension extends \Twig_Extension {

  /**
   * @return array
   */
  public function getFunctions()
  {
    return [
      new \Twig_SimpleFunction('renderMenu', [$this, 'renderMenu'])
    ];
  }

  /**
   * Provides function to programmatically rendering a menu
   *
   * @param String $menu_name
   *   The machine configuration id of the menu to render
   */
  public function renderMenu(string $menu_name) {
    $menu_tree = \Drupal::menuTree();

    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

    // Load the tree based on this set of parameters.
    $tree = $menu_tree->load($menu_name, $parameters);

    // Transform the tree using the manipulators you want.
    $manipulators = array(
      // Only show links that are accessible for the current user.
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      // Use the default sorting of menu links.
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);

    // Finally, build a renderable array from the transformed tree.
    $menu = $menu_tree->build($tree);

    $menu['#attributes']['class'] = 'menu ' . $menu_name;

    return array('#markup' => drupal_render($menu));
  }

}

Code source : https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Menu!menu.api.php/group/menu/8#sec_rendering

In your custom_module.services.yml write:

  custom_module.render_menu_extension:
      class: Drupal\custom_module\Twig\RenderMenuExtension
      tags:
        - { name: twig.extension }

Then in your twig template, your can call the following funciton with the machine name of your menu as follows :

{{ render_menu('my_menu') }}

Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *