【问题标题】:Symfony2 pass variable from own bundle to twigSymfony2将变量从自己的包传递到树枝
【发布时间】:2016-03-15 00:00:08
【问题描述】:

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

我需要为这个包定义一个可以在树枝模板中使用的变量。

当我尝试在我的 bundle 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

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 }}

【问题讨论】:

标签: php symfony twig


【解决方案1】:

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

在您的 bundle Container Extension 中,您可以将配置值传递给容器参数,然后将这些参数作为构造函数参数传递给 Twig Extension。

但是,正如 Alex 已经指出的那样,在将 Twig Extension 添加到容器之前,您需要检查 Twig Bundle 是否已加载且可用。

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

【讨论】:

  • 也许一个代码示例会更有启发性,我更新了我的问题,用代码示例添加了答案。感谢您的回答;)
  • 我只在火车上玩手机。对不起。
  • 非常感谢,知道怎么处理就够了。
【解决方案2】:

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

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);
    }

然后你可以在 twig 中使用 my_global_twig_variable_name。

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 2015-04-22
    • 1970-01-01
    • 2013-08-08
    • 2014-08-31
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    相关资源
    最近更新 更多