Accessing session from TWIG template

后端 未结 5 565
长发绾君心
长发绾君心 2020-11-29 22:26

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 whe

5条回答
  •  孤独总比滥情好
    2020-11-29 22:44

    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:

     $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 }}
    

提交回复
热议问题