Symfony2 pass variable from own bundle to twig

Viewed 2107

I'm developing a third party bundle.

I need to define a variable that can be used in a twig template for this bundle.

when trying to declare in my bundle config.yml mode in which the variables step twig templates on my projects,

twig:
    globals:
        test_vars: %test_vars%

I get this error.

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

thanks a lot


Solution code, thanks to @alexander.polomodov and @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 }}
2 Answers

I had the same case (passing an own bundle config value to a twig template), my actually working solution is to pass the config value as a twig global in my bundle extension :

1 - your bundle's extension should extends PrependExtensionInterface, see https://symfony.com/doc/current/bundles/prepend_extension.html

2 - you implement prepend method doing this :

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

Then you can use my_global_twig_variable_name in twig.

Related