I've searched a lot on the net how to access the global $_SESSION
array from TWIG template and found this: {{app.session.get('index')}}
, but when I'm calling it, it returns an empty string. I have a $_SESSION['filter']['accounts']
and I'm getting this error when calling {{app.session.get('filter').accounts}}
: Item "accounts" for "" does not exist
. What I'm doing wrong?
A simple trick is to define the $_SESSION array as a global variable. For that, edit the core.php file in the extension folder by adding this function :
public function getGlobals() {
return array(
'session' => $_SESSION,
) ;
}
Then, you'll be able to acces any session variable as :
{{ session.username }}
if you want to access to
$_SESSION['username']
The way to access a session variable in Twig is:
{{ app.session.get('name_variable') }}
Setup twig
$twig = new Twig_Environment(...);
$twig->addGlobal('session', $_SESSION);
Then within your template access session values for example
$_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template
I found that the cleanest way to do this is to create a custom TwigExtension and override its getGlobals()
method. Rather than using $_SESSION
, it's also better to use Symfony's Session
class since it handles automatically starting/stopping the session.
I've got 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 in /app/config/services.yml:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
Then the session can be accessed from any view using:
{{ session.my_variable }}
Source: Stackoverflow.com