0

I'm trying to access the session variables in the twig which is set in the controller. For some reasons it's not working in twig. I have checked the session variables printing in another controller which is giving the expected result but the variable shows empty in template. I don't know whether I'm missing something in configuration.

//Below is my code in controller

$session = $request->getSession();
$session->set('user', [
    'id' => $user->getId(), 
    'firstName' => $user->getfirstname()
]);

// code in twig
{{ dump(app.session) }}
3
  • Are you handing the $session variable over to twig? Commented Jul 20, 2016 at 13:36
  • No. I'm not passing $session variable over to twig. I'm thinking its global configuration hence explicitly not passing the $session array over to twig. Am I wrong? Commented Jul 20, 2016 at 13:46
  • Oh, stupid me! You are of course right regarding the global variable. Commented Jul 20, 2016 at 13:59

2 Answers 2

1

No, don't presume that session variables are global.

I've done this and you need to pass via array when rendering your Twig. Something like this:

return $this->render('my_twig_file.html.twig', array(
        'user' => $session->get('user'),
));

Then in Twig dump it:

{{ dump(user) }}

Also, make sure you don't use dump in your PROD environment. You might want to comment the dump out when you are done testing, or use a different file.

Sign up to request clarification or add additional context in comments.

Comments

0

I have found a solution on myself. I have used the custom twig extension to access the global variables like session without any issues. Just find the code below.

http://symfony.com/doc/current/cookbook/templating/twig_extension.html

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.