Get a session value in a template file
Question
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);
Solution
I solved this by send session variable in theme template_preprocess and then call the variable in the twig file.
template.theme :-
template_preprocess($variables){
$session = \Drupal::request()->getSession();
$variables['abc'] = $session->get('abc');
}
Call variable in twig file :-
{{ abc }}
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange