Error when creating a custom Twig filter I'm trying to create a custom Twig filter in Drupal 8. The goal is to use my custom filter in a template like so:

{{ a_variable|myfilter }}


I have created a custom module with 3 files:

MODULE.info.yml
MODULE.services.yml
src/TwigExtension/MyExtension.php


The MODULE.info.yml file contains the usual values.

The MODULE.services.yml file contains:

services:
  MODULE.twig_extension:
#   arguments: ['@renderer']  #  &lt;-- Initial code (USELESS)
    class: Drupal\MODULE\TwigExtension\MyExtension
    tags:
      - { name: twig.extension }


The src/TwigExtension/MyExtension.php file contains:

namespace Drupal\MODULE\TwigExtension;

// use Drupal\Core\Template\TwigExtension;  // &lt;-- Initial code (WRONG)

class MyExtension extends \Twig_Extension {    
// class MyExtension extends TwigExtension {  // &lt;-- Initial code (WRONG)

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters() {
    return [
      new \Twig_SimpleFilter('myfilter', array($this, 'myFilter')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName() {
    return 'MODULE.twig_extension';
  }

  /**
   * Replaces all instances of "animal" in a string with "plant".
   */
  public static function myFilter($string) {
    return str_replace(array('animal'), array('plant'), $string);
  }

}


My initial code got following error: "Call to a member function generateFromRoute() on a non-object in /core/lib/Drupal/Core/Template/TwigExtension.php on line 224".

But I have now corrected the code following lauriii's answer and it works perfectly!
The problem in the code above is that your Twig extension class is extending the internal Drupal Twig extension class. That breaks the Twig extensions added by Drupal core and that's why you are getting the error.

To fix this, you should make your Twig extensions extend Twigs internal Twig extension class. Your class should be defined like this:

class MyExtension extends \Twig_Extension {


After making that change, you can also remove arguments set for that class from the MODULE.services.yml