2013-02-05 53 views
2

如何告訴Symfony2不要在模板中設置全局變量(如app)?我想設置我自己的app變量,但它有Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables Object類型的事件,如果我覆蓋它在我的控制器。如何防止Symfony 2在模板中設置全局變量?

+7

難道你不能只使用自己的變量爲你的應用程序對象,如'myapp'而不是'app'?通過更改框架的內置行爲,您的代碼將變得非常不便。 – leftclickben

+4

難道你不能使用'my_app'而不是'app'嗎?我不確定這一點,但Symfony的一些內部可能依賴於這個變量。 –

回答

1

我認爲是這樣的可能性(基本上從來沒那麼引起app變種都能得心應手;))

app全球在Symfony\Bundle\TwigBundle\TwigEngine(用於樹枝構造函數添加),並在Symfony\Bundle\FrameworkBundle\Templating\PhpEngine構造函數(對於PHP)

但是當你不通過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); 
    } 
} 

你應該知道,你可以實現自己的全局不作爲以及...只是定義自己的templating.globals服務,將取代原來的一個。