“未知过滤器"的 Twig_Error_Syntax在 Timber 中使用 Twig 过滤器

2022-01-22 00:00:00 php wordpress twig timber

这一定很简单,但我看不出有什么问题.我在 https://twig.symfony 使用简单的过滤器示例.com/doc/1.x/advanced.html#filters Twig 1.34 in Timber,一个 WordPress 插件.

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.

我加了

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

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

到我的主题的functions.php文件.

to my theme's functions.php file.

但在我的 view.twig 文件中使用 {{ 'Twig'|rot13 }} 会出现致命错误

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

还有通知

Undefined variable: loader in functions.php

使用像 {{ 'Twig'|lower }} 这样的过滤器可以正常工作.

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

我需要以不同的方式将函数添加到functions.php吗?

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

推荐答案

根据文档 这里(标题:添加到 Twig)

应该这样做(在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;
});

相关文章