Would be much appreciated an example of a plugin that add custom twig filters.
Thanks
There are two main parts to this question:
-
First you need to create a Twig extension file that provides the filters. An example of this can be found in TwigExtension.php file that we provide in the Grav core. You can use this as an example, as it has quite a few handy filters in it. You can just create your own and provide it with the plugin.
-
The next part is the plugin itself, it really only needs to provide a method for the
onTwigExtensions
event, and that is where you would add the extension with something like:
require_once(__DIR__ . '/CustomTwigFilters.php';
$this->grav['twig']->twig->addExtension(new CustomTwigFilters());
Obviously this assumes you have a created a Twig extension called CustomTwigFilters and saved it in a file called CustomTwigFilters.php.
Something like that should work fine.
Thanks, I tried this, but I got this error :
Call to a member function addExtension() on a non-object
on the line : $this->grav[‘twig’]->twig->addExtension(new CustomTwigFilters());
the class CustomTwigFilters() is being required and seems to be fine.
I’ll need to see all your code for the plugin to know what’s going on.
you need to change CustomTwigFilters() with \Grav\Common\CustomTwigFilters() because you are in this namespace