扩展Twig的AppVariable

Ant*_*ony 2 php symfony twig

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

该网站运行正常,直到我运行composer升级包.它将Symfony 2.6升级到2.7.1,将Twig 1.18升级到1.18.2.

我现在收到以下错误:

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

有问题的twig文件有这样的调用:

{{ app.site.name }}
Run Code Online (Sandbox Code Playgroud)

现在显然site不是该AppVariable类型的成员.我无法弄清楚原始开发人员是如何app通过新成员扩展Twig的全球性的.我真的不知道在哪里看.我对Symfony不太称职.

Art*_*iel 9

旧开发人员可能做的事情是覆盖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);
    }

}
Run Code Online (Sandbox Code Playgroud)

然后注册:

services:
    app.super_globals_extended:
        class: AppBundle\Service\SuperGlobalsExtended
        arguments:
            - @service_container
Run Code Online (Sandbox Code Playgroud)

最后但并非最不重要的是,覆盖app树枝的变量:

twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"
    globals:
        app: @app.super_globals_extended
Run Code Online (Sandbox Code Playgroud)

现在,您可以在扩展类中定义自己的方法,也可以访问此处已有的先前方法.

对于symfony @ 2.7是相同的,只是类名不同.在这里我扩展了GlobalVariables,但对于@ 2.7你必须扩展AppVariable.

位于TwigBundle Resources文件夹中的@ 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>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.