2016-03-15 97 views
3

我正在開發第三方包。Symfony2從自己的包到樹枝傳遞變量

我需要定義一個變量,該變量可用於此捆綁的樹枝模板。

想在我捆config.yml模式,其中的變量在我的項目步驟樹枝模板聲明時

twig: 
    globals: 
     test_vars: %test_vars% 

我得到這個錯誤。

InvalidArgumentException in YamlFileLoader.php line 357: 
There is no extension able to load the configuration for "twig" (in /home/domain.ext/vendor/test/test-bundle/test/TestBundle/DependencyInjection/../Resources/config/.yml). Looked for namespace "twig", found none 

非常感謝


解決方案的代碼,感謝@ alexander.polomodov和@mblaettermann

GlobalsExtension.php

namespace Vendor\MyBundle\Twig\Extension; 

class GlobalsExtension extends \Twig_Extension { 

    public function __construct($parameter) { 
     $this->parameter= $parameter; 
     //... 
    } 

    public function getGlobals() { 

     return array(
      'parameter' => $this->parameter 
      //... 
     ); 
    } 

    public function getName() { 
     return 'MyBundle:GlobalsExtension'; 
    } 
} 

my.yml

services: 
    twig.extension.globals_extension: 
     class: Vendor\MyBundle\Twig\Extension\GlobalsExtension 
     arguments: [%my.var%] 
     tags: 
      - { name: twig.extension } 

my.html.twig

my parameter: {{ parameter }} 
+4

是否包含TwigBundle在AppKernel和設置在樹枝應用程序配置?請參閱github上有關symfony標準的文件鏈接: https://github.com/symfony/symfony-standard/blob/2.8/app/config/config.yml#L34-37, https:// github。 com/symfony/symfony-standard/blob/2.8/app/AppKernel.php#L13 –

+0

感謝您的提示 –

回答

2

你應該完全在你自己的包使用依賴注入實現這個邏輯。這意味着,不要劫持twig:配置密鑰,而是使用您自己的軟件包配置密鑰。

在您的bundle Container Extension中,您可以將配置值傳遞給容器參數,然後將其作爲構造函數參數傳遞給Twig Extension。

但是,如Alex已經指出的那樣,在將Twig Extension添加到容器之前,您需要檢查Twig Bundle是否已加載並可用。

http://symfony.com/doc/current/cookbook/templating/twig_extension.html

+1

也許一個代碼示例會更具啓發性,我更新了我的問題,並在代碼示例中添加了答案。感謝您的回答;) –

+0

我只在列車上使用手機。抱歉。 – mblaettermann

+1

非常感謝,知道如何處理它就足夠了。 –