Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Archive

Twig filters example

Started by Muut Archive 12 years ago · 4 replies · 277 views
12 years ago

Would be much appreciated an example of a plugin that add custom twig filters.
Thanks

12 years ago

There are two main parts to this question:

  1. 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.

  2. 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:

PHP
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.

12 years ago

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.

12 years ago

I'll need to see all your code for the plugin to know what's going on.

12 years ago

you need to change CustomTwigFilters() with \Grav\Common\CustomTwigFilters() because you are in this namespace :)

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1280 9 years ago
Archive · by Muut Archive, 9 years ago
2 888 9 years ago
Archive · by Muut Archive, 9 years ago
2 4016 9 years ago
Archive · by Muut Archive, 9 years ago
1 2892 9 years ago
Archive · by Muut Archive, 9 years ago
3 1076 9 years ago