“未知过滤器"的 Twig_Error_Syntax在 Timber 中使用 Twig 过滤器 [英] Twig_Error_Syntax for "Unknown filter" with a Twig filter in Timber

查看:14
本文介绍了“未知过滤器"的 Twig_Error_Syntax在 Timber 中使用 Twig 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一定很简单,但我看不出有什么问题.我在 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;
});

这篇关于“未知过滤器"的 Twig_Error_Syntax在 Timber 中使用 Twig 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆