Symfony2 将变量从自己的捆绑包传递到树枝


Symfony2 pass variable from own bundle to twig

我正在开发一个第三方捆绑包。

我需要定义一个变量,该变量可用于此捆绑包的树枝模板。

当尝试在我的捆绑包 config.yml 模式下声明变量在我的项目上步进 twig 模板时,

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

全局扩展.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';
    }
}

我的.yml

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

我的.html.树枝

my parameter: {{ parameter }}
您应该

使用依赖注入在自己的捆绑包中完全实现此逻辑。这意味着,不要劫持twig:配置密钥,而是使用您自己的捆绑配置密钥。

在捆绑包容器扩展中,您可以将配置值传递到容器参数中,然后作为构造函数参数传递给 Twig 扩展。

但是,正如

Alex 已经指出的那样,在将 Twig 扩展添加到容器之前,您需要检查 Twig 捆绑包是否已加载且可用。

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

我有同样的情况(将自己的捆绑包配置值传递给树枝模板),我实际工作的解决方案是将配置值作为我的捆绑包扩展中的树枝全局传递:

1 - 您的捆绑包的扩展应该扩展 PrependExtensionInterface,请参阅 https://symfony.com/doc/current/bundles/prepend_extension.html

2 - 您实现这样做的 prepend 方法:

    public function prepend(ContainerBuilder $container)
    {
// get configuration from config files
        $configs     = $container->getExtensionConfig($this->getAlias());
        $config      = $this->processConfiguration(new Configuration(), $configs);
// put your config value in an array to be passed in twig bundle
        $twigGlobals = [
            'globals' => [
                'my_global_twig_variable_name' => $config['myConfigKey'],
            ],
        ];
// pass the array to twig bundle
        $container->prependExtensionConfig('twig', $twigGlobals);
    }

然后你可以在树枝中使用my_global_twig_variable_name。