2

I'm trying to write a simple twig extension to render a menu inside twig template files.

I created a custom module for this purpose. It's folder structure looks like this:

-modules
--MenuRender
---src
----MenuRenderExtension.php
--menurender.info.yml
--menurender.services.yml

The *.info file is a standard file, the *.services files looks like this:

services:
  menurender.twig_extension:
    class: Drupal\MenuRender\MenuRenderExtension
    tags:
      - { name: twig.extension }

And the MenuRenderExtension class is as follows:

namespace Drupal\MenuRender;

class MenuRenderExtension extends \Twig_Extension {

  public function getName() {
    return 'MODULE.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($menu_name) {
    // 50+ lines so i cut this part as it's mostly clean PHP
  }

}

I am constantly getting this error msg in apache's error log

Service 'menurender.twig_extension' for consumer 'twig' does not implement Twig_ExtensionInterface

Any one have a clue ? p.s. new to drupal8

  • 2
    Your module name should not be camel case, but should instead be mymodule. Your namespace needs to reflect that, too. It should likely live under a folder in src called TwigExtension, too. See: cgit.drupalcode.org/twig_blocks/tree/src/Twig/… – Kevin Jun 26 '17 at 14:34
  • 1
    PS I think what you are trying to achieve has been done, in some form, here: drupal.org/project/simplify_menu – Kevin Jun 26 '17 at 14:37
  • @Kevin Wow you're right! It works! Wasted 2h because of such a stupid thing. Thank you very much. – lordZ3d Jun 27 '17 at 12:03
  • I'll add it as the answer. – Kevin Jun 27 '17 at 13:17
1

Your module name should not be camel case, but should instead be mymodule (not MenuRender). Your namespace needs to reflect that, too. It should likely live under a folder in src called TwigExtension, and your module name in the namespace should match the directory (i.e. Drupal\mymodule, not Drupal\MyModule).

Here is a module that uses TwigExtension for comparison.

What's likely happening is the application is unable to locate certain things due to the file naming and namespacing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.