5
votes

This has got to be simple, but I can't see what's wrong. I'm using the simple filter example at https://twig.symfony.com/doc/1.x/advanced.html#filters with Twig 1.34 in Timber, a WordPress plugin.

I added

// an anonymous function
$filter = new Twig_SimpleFilter('rot13', function ($string) {
    return str_rot13($string);
});

and

$twig = new Twig_Environment($loader);
$twig->addFilter($filter);

to my theme's functions.php file.

But using {{ 'Twig'|rot13 }} in my view.twig file gives a fatal error

PHP Fatal error:  Uncaught exception 'Twig_Error_Syntax'
with message 'Unknown "rot13" filter' in view.twig

and a notice

Undefined variable: loader in functions.php

Using a filter like {{ 'Twig'|lower }} works OK.

Do I need to add the functions to functions.php in a different way?

1
I'd say yes, most likely you need to. Perhaps it's just no the correct place for that view.twig file. - hakre
OK, but how to do that is my question. - BlueDogRanch
From what I read from the docs you do everything right. I think only the where to do that is not so clear (for me as well). So the how looks good to me honestly. - hakre
True, the docs are not clear about where the php functions go. And there is a global function listed that "is like any other template variable, except that it's available in all templates and macros" but it's not clear how to use it. - BlueDogRanch
Now that's a hint. $loader is not defined. You need to write that code where $loader is defined otherwise it can't work. - hakre

1 Answers

3
votes

According to documentation here (title: Adding to Twig)

it should be done like this (in functions.php):

add_filter('timber/twig', function($twig) {
   $twig->addExtension(new Twig_Extension_StringLoader());

   // add Your filters here
   $twig->addFilter(
     new Twig_SimpleFilter(
       'rot13', 
       function($string) {
         return str_rot13($string);
       }
     )
   );
   // or simply: 
   // $twig->addFilter(new Twig_SimpleFilter('rot13', 'str_rot13'));

   $twig->addFilter(
     new Twig_SimpleFilter(
       'hello', 
       function($name) {
         return 'Hello, '.$name;
       }
     )
   );

   return $twig;
});