Twig_Error_Syntax for “Unknown filter” with a Twig filter in Timber

倖福魔咒の 提交于 2019-12-04 04:05:44

问题


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:


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;
});


来源:https://stackoverflow.com/questions/49836358/twig-error-syntax-for-unknown-filter-with-a-twig-filter-in-timber

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!