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'] # <-- 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; // <-- Initial code (WRONG)
class MyExtension extends \Twig_Extension {
// class MyExtension extends TwigExtension { // <-- 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!
TwigExtension
with\Twig_Extension
. ;-)