Expose config.yml values globally for Twig templates in Symfony2 applications

Lets suppose you have created a bundle that has some specific configuration in the config.yml file (this is done by exposing semantic configuration). For example the languages supported by the application:

acme_demo:
    languages:
        en: English
        es: Spanish (Español)

You could make all your controllers read this language configuration from the container interface and then expose that variable to the templates like this:

// src/Acme/DemoBundle/Controller/AcmeController.php
$this->languages = $this->container->getParameter('acme_demo.languages');
    }

    public function indexAction()
    {
        return $this->render('AcmeDemoBundle:Default:index.html.twig',
                array('languages' => $this->languages)
        );
    }
}
// src/Acme/DemoBundle/Resources/views/Default/index.html.twig
{% for lang, language in languages %}
                    {{ lang }} - {{ language }}
{% endfor %}

But this would be VERY tedious. A much better approach is to create a Twig extension that exposes that configuration readed from the container interface as it would be done inside config.yml in the twig:globals section:

// src/Acme/DemoBundle/Twig/LanguageExposeExtension.php
container = $container;
    }
    
    public function getGlobals()
    {
        return array(
            'languages' => $this->container->getParameter('acme_demo.languages')
        );
    }
    
    public function getName()
    {
        return 'language_expose_extension';
    }
}

And of course register this class as a Twig extension using the twig.extension tag:

// src/Acme/DemoBundle/Resources/config/services.yml
services:
    acme.twig.language_expose_extension:
        class: Acme\DemoBundle\Twig\LanguageExposeExtension
        arguments: []
        tags:
            - { name: twig.extension }

Now you can remove the language parameter in the render call because it’s now defined globally for all templates.

You might also like

Symfony2 routing: Allow dots in URL
I have one route in my app that must have a text and a dot followed by a format. For example: http://domain.com/image/mi-text-with-dots-.-in-.-the-.-middle.png As...
Symfony2 – ErrorException: Notice: serialize() [function.serialize]: “xxx” returned as member variable from __sleep() but does not exist in …
While storing an entity from Doctrine2 in the session under a Symfony2 application I got this error: ErrorException:...
Fix “Cannot redeclare class Symfony\…” in Symfony2 after upgrade
After upgrading from Symfony 2.2 to 2.3 I got this error in my application: Fatal error: Cannot redeclare...
Fix black screen in Raspberry Pi with HDMI to VGA adapter
If you use an HDMI to VGA adaptor and get a black screen you may tweak the config.txt to solve the problem. If...
Leave a comment ?

1 Comments.

  1. This post has been my salvation. I am so thankfull. Tx

    Reply

Leave a Comment