1

I have set a custom value in the session variable from the PHP class now I want to get the Session variable in the twig template in shopware6. anyone can help me?

  • Does this answer your question? [Accessing session from TWIG template](https://stackoverflow.com/questions/8399389/accessing-session-from-twig-template) – j_elfering Jan 18 '23 at 08:47

1 Answers1

4

It's not considered best practice to access the session directly in the template. You should create a subscriber to add variables to your template.

class MySubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            GenericPageLoadedEvent::class => 'onPageLoaded',
        ];
    }
    
    public function onPageLoaded(GenericPageLoadedEvent $event): void
    {
        $session = $event->getRequest()->getSession();

        $event->getPage()->assign(['myVariable' => $session->get('someSessionKey')]);
    }
}

Then in your template:

{{ page.myVariable }}

For the sake of completion: You can also access the session object in the template directly.

{{ app.session.get('someSessionKey') }}

I'd still recommend going the extra mile with a subscriber to do some sanity checks though.

dneustadt
  • 12,015
  • 1
  • 12
  • 18