从TWIG模板访问会话
我在网上search了很多如何从TWIG模板访问全局$_SESSION数组,并发现这个: {{app.session.get('index')}} ,但是当我调用它时,它返回一个空的string。 我有一个$_SESSION['filter']['accounts'] ,当调用{{app.session.get('filter').accounts}}时,出现这个错误: Item "accounts" for "" does not exist 。 我做错了什么? 
  {{app.session}}引用Session对象而不是$_SESSION数组。 我不认为$_SESSION数组是可访问的,除非你明确地将它传递给每个Twig模板,或者如果你做一个扩展,使其可用。 
  Symfony2是面向对象的,所以你应该使用Session对象来设置会话属性而不是依赖数组。  Session对象会将这些东西从你身上抽象出来,所以将会话存储在数据库中比较容易,因为存储会话variables对你来说是隐藏的。 
 所以,在会话中设置你的属性,并使用Session对象检索你的树枝模板中的值。 
 // 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'] %} 
希望这可以帮助。
 问候, 
 马特 
一个简单的技巧是将$ _SESSION数组定义为一个全局variables。 为此,通过添加以下函数来编辑扩展文件夹中的core.php文件:
 public function getGlobals() { return array( 'session' => $_SESSION, ) ; } 
然后,您将能够访问任何会话variables,如下所示:
 {{ session.username }} 
如果你想访问
 $_SESSION['username'] 
设置树枝
 $twig = new Twig_Environment(...); $twig->addGlobal('session', $_SESSION); 
然后在您的模板中访问会话值
 $_SESSION['username'] in php file Will be equivalent to {{ session.username }} in your twig template 
 我发现最干净的方法是创build一个自定义的TwigExtension并覆盖它的getGlobals()方法。 而不是使用$_SESSION ,最好使用Symfony的Session类,因为它处理自动启动/停止会话。 
我在/src/AppBundle/Twig/AppExtension.php中有以下扩展名:
 <?php namespace AppBundle\Twig; use Symfony\Component\HttpFoundation\Session\Session; class AppExtension extends \Twig_Extension { public function getGlobals() { $session = new Session(); return array( 'session' => $session->all(), ); } public function getName() { return 'app_extension'; } } 
然后将其添加到/app/config/services.yml中 :
 services: app.twig_extension: class: AppBundle\Twig\AppExtension public: false tags: - { name: twig.extension } 
然后可以从任何视图访问会话使用:
 {{ session.my_variable }} 
在Twig中访问会话variables的方法是:
 {{ app.session.get('name_variable') }} 
为什么不使用{{app.object name.field name}}来访问variables?