扩展Twig的AppVariable

安东尼

我继承了一个使用Symfony 2的网站。

在我运行作曲家升级软件包之前,该网站运行良好。它将Symfony 2.6升级到2.7.1,并将Twig 1.18升级到1.18.2。

我现在收到以下错误:

对象“ Symfony \ Bridge \ Twig \ AppVariable”的方法“站点”在第21行的@ Page / Page / homepage.html.twig中不存在

有问题的树枝文件具有如下调用:

{{ app.site.name }}

现在显然site不是该AppVariable类型的成员我在弄清楚原始开发人员如何app通过新成员扩展Twig的全球范围时遇到了麻烦我真的不知道在哪里看。我对Symfony并不太胜任。

阿塔米尔

老开发人员可能所做的就是覆盖app变量。在Symfony @ 2.7之前,该类已被调用GlobalVariables并位于以下命名空间-中Symfony\Bundle\FrameworkBundle\Templating从@ 2.7开始,它被调用AppVariable,并且位于此命名空间-中Symfony\Bridge\Twig在幕后做什么?

使用addGlobalTwig的方法将包含全局变量的类简单地添加为twig全局变量,并为其值app将整个类注入为已定义的服务。GlobalVariablesAppVariables接受服务容器作为参数,并默认定义5种可在我们的模板中使用的方法。我将向您展示扩展该类的简单方法,以便您可以使用它进行调查。

创建我们将定义为服务的简单类:

<?php

namespace AppBundle\Service;

use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables,
    Symfony\Component\DependencyInjection\ContainerInterface;

class SuperGlobalsExtended extends GlobalVariables {

    /**
     * @var ContainerInterface
     **/
    protected $container = null;

    public function __construct(ContainerInterface $container) {
        $this->container = $container;

        parent::__construct($container);
    }

}

然后注册:

services:
    app.super_globals_extended:
        class: AppBundle\Service\SuperGlobalsExtended
        arguments:
            - @service_container

最后但并非最不重要的一点是,覆盖twig的app变量:

twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    globals:
        app: @app.super_globals_extended

现在,您可以在扩展类中定义自己的方法,并访问此处已经存在的先前方法。

因为symfony @ 2.7是相同的,只是类名不同。在这里,我扩展GlobalVariables,但是对于@ 2.7,您必须扩展AppVariable

位于TwigBundle资源文件夹中的@ 2.7服务定义。

<service id="twig" class="%twig.class%">
        <argument type="service" id="twig.loader" />
        <argument /> <!-- Twig options -->
        <call method="addGlobal">
            <argument>app</argument>
            <argument type="service" id="twig.app_variable" />
        </call>
        <configurator service="twig.configurator.environment" method="configure" />
    </service>

希望这可以帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章