如何防止Symfony 2在模板中设置全局变量


How to prevent Symfony 2 from setting global variables in templates?

如何告诉Symfony2不要在模板中设置全局变量(如app)?我想设置我自己的app变量,但如果我在控制器中覆盖它,它会有Symfony'Bundle'FrameworkBundle'Templating'GlobalVariables Object类型的事件。

我认为这就是这样的可能性(基本上从来没有这样做过,因为app var可以很方便;)

app全局添加在Symfony'Bundle'TwigBundle'TwigEngine的构造函数中(对于trick)和Symfony'Bundle'FrameworkBundle'Templating'PhpEngine的构造函数中

但当您不将GlobalVariables传递给构造函数(可以为null)时,它不会设置app变量。所以你可以这样覆盖templating服务:

    <service id="templating" class="Acme'DemoBundle'Templating'TwigEngine">
        <argument type="service" id="twig" />
        <argument type="service" id="templating.name_parser" />
        <argument type="service" id="templating.locator" /> 
    </service>

和php文件:

<?php 
namespace Acme'DemoBundle'Templating;
use Symfony'Bundle'TwigBundle'TwigEngine as BaseEngine;
use Symfony'Component'Templating'TemplateNameParserInterface;
use Symfony'Component'Config'FileLocatorInterface;
class TwigEngine extends BaseEngine
{
    public function __construct('Twig_Environment $environment, TemplateNameParserInterface $parser, FileLocatorInterface $locator)
    { 
        parent::__construct($environment, $parser, $locator);
    } 
}

您应该意识到,您也可以在没有这些的情况下实现自己的全局。。。只需定义自己的CCD_ 11服务,它将取代原来的服务。