68

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?

1
  • 13
    Do NOT use $_SESSION in Symfony!
    – Gigala
    Apr 19, 2013 at 9:24

6 Answers 6

155

{{app.session}} refers to the Session object and not the $_SESSION array. I don't think the $_SESSION array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.

Symfony2 is object-oriented, so you should use the Session object to set session attributes and not rely on the array. The Session object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.

So, set your attribute in the session and retrieve the value in your twig template by using the Session object.

// In a controller
$session = $this->get('session');
$session->set('filter', array(
    'accounts' => 'value',
));

// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}
3
  • 1
    thanks :) this helped me P.S. you need to change your answer as this: $session->set('filter', array( 'accounts' => 'value' ));
    – haynar
    Dec 6, 2011 at 13:21
  • What if sessions are stored in Memcached ? May 25, 2014 at 14:37
  • @Sekai doesnt make a differnce i would say if you configured it correctly
    – Gigala
    Jul 28, 2015 at 7:55
35

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
6
  • This is a great answer. Aug 30, 2016 at 17:12
  • Yes, great answer.
    – JimB814
    Sep 10, 2016 at 1:46
  • Yes, great answer
    – migli
    Mar 1, 2018 at 10:43
  • 1
    Great answer because it works without Symphony. Not shown is how to do this within the view container, which is very similar. Where $view is the newly created Twig object, add the following to the container function (the same place you might add extensions). $view->getEnvironment()->addGlobal('session', $_SESSION);
    – alttag
    Mar 16, 2019 at 22:28
  • This code does not work in the latest Twig version. @user1279047 Jan 21, 2020 at 9:45
22

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']
3
  • 8
    This is a much better answer than the above, given that you can be using Twig without using Symfony.
    – gazarsgo
    Jan 8, 2013 at 0:39
  • 6
    Rather than edit core.php though follow the docs here: twig.sensiolabs.org/doc/advanced.html
    – gazarsgo
    Jan 8, 2013 at 4:26
  • 2
    @gazarsgo Both solutions are just great.
    – pregmatch
    Nov 29, 2013 at 12:19
20

The way to access a session variable in Twig is:

{{ app.session.get('name_variable') }}
7

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 }}
2
  • This is nice. How can i set a session variable in twig using this solution??
    – Ranhot
    Jan 24, 2018 at 11:54
  • 2
    @Ranhot, you shouldn't set session variables in twig views. That should be done in controllers or services.
    – laurent
    Jan 24, 2018 at 14:31
0

I found that in Grav CMS you could access session variables from twig like this:

{{ grav.session.variable }}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.