I am trying to get value set in session in a template file, but I don't get the expected value. I tried two methods, but neither of them works for me.

The code in the custom module controller is the following.

$xyz ='tets';
$session = \Drupal::request()->getSession();
//$session->set('xyz', $roles);
$session->set('abc', $xyz);

The code in the template file is the following.

{% set varname = app.session.get('abc') %}
{{ varname }}

I tried using the following code as well.

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('num_donateur', $num_donateur);
  • Pass the variable in in your template_preprocess() function.
    – Cool
    Sep 18, 2020 at 12:21
  • do I need use $session = \Drupal::request()->getSession(); in template_preprocess() function template_preprocess(&$variables, $hook){ $session = \Drupal::request()->getSession(); $variables['abc'] = $session->get('abc'); } Sep 18, 2020 at 13:01
  • you can use user.private_tempstore. And use the respective preprocess function based on in which template file you need the value. for example: if you need in ´node.html.twig´ then use ´yourtheme_preprocess_node(&$variables) { }´function.
    – Cool
    Sep 18, 2020 at 13:15
  • 2
    You usually set a session value in a POST request. When doing it in a controller you have to disable caching for this controller. When displaying the session value like in your comment then add a cache context for the session to the render array. See drupal.stackexchange.com/a/273752/47547
    – 4uk4
    Sep 18, 2020 at 21:20

1 Answer 1


I solved this by send session variable in theme template_preprocess and then call the variable in the twig file.

template.theme :-

   $session = \Drupal::request()->getSession();
   $variables['abc'] = $session->get('abc'); 

Call variable in twig file :-

{{ abc }}

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.