I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals() method. Instead of using $_SESSION also better to use the Symfony Session class, since it automatically starts / stops a session.
I have the following extension in /src/AppBundle/Twig/AppExtension.php :
<?php namespace AppBundle\Twig; use Symfony\Component\HttpFoundation\Session\Session; class AppExtension extends \Twig_Extension { public function getGlobals() { $session = new Session(); return array( 'session' => $session->all(), ); } public function getName() { return 'app_extension'; } }
Then add this to /app/config/services.yml :
services: app.twig_extension: class: AppBundle\Twig\AppExtension public: false tags: - { name: twig.extension }
Then, access to the session can be obtained from any view using:
{{ session.my_variable }}
this.lau_ Aug 27 '15 at 14:48 2015-08-27 14:48
source share