Symfony2如何将自己的bundle中的变量传递给Twig模板?

4

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

我需要定义一个变量,以便在twig模板中使用该变量。

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

4
你在 AppKernel 中是否包含了 TwigBundle 并在应用程序配置中设置了 Twig?查看 symfony-standard 的 github 上这些文件的链接: 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 - alexander.polomodov
感谢您的留言。 - jjgarcía
2个回答

2
你应该完全在自己的bundle中使用依赖注入来实现这个逻辑。这意味着不要劫持twig:配置键,而是使用自己的bundle配置键。
在你的bundle的Container Extension中,你可以将你的配置值传递到容器参数中,然后作为构造函数参数传递给Twig Extension。
但是,在将Twig Extension添加到容器之前,你需要检查Twig Bundle是否已加载和可用,就像Alex已经指出的那样。

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


1
也许一个代码示例会更有教育意义,我更新了我的问题,并添加了带有代码示例的答案。感谢您的回答;) - jjgarcía
我只能在火车上使用手机,抱歉。 - mblaettermann
1
非常感谢,知道如何处理它已经足够了。 - jjgarcía

1
我曾经遇到过同样的问题(将自己的Bundle配置值传递给Twig模板),我的解决方案是在Bundle扩展中将配置值作为Twig全局变量传递:

1- 你的Bundle扩展应该扩展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中使用我的全局Twig变量名称。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接