Accessing session from TWIG template

后端 未结 5 566
长发绾君心
长发绾君心 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:51

    {{app.session}} refers to the Session object and not the $_SESSION array. I don't think the $_SESSION array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.

    Symfony2 is object-oriented, so you should use the Session object to set session attributes and not rely on the array. The Session object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.

    So, set your attribute in the session and retrieve the value in your twig template by using the Session object.

    // In a controller
    $session = $this->get('session');
    $session->set('filter', array(
        'accounts' => 'value',
    ));
    
    // In Twig
    {% set filter = app.session.get('filter') %}
    {% set account-filter = filter['accounts'] %}
    

    Hope this helps.

    Regards,
    Matt

提交回复
热议问题