将会话传递给TWIG模板

viy*_*ncs 3 php slim twig

当我想$_SESSION['session'];使用slim micro Framework进入twig模板时,我有一个问题.

这是我的代码:

<!DOCTYPE html>
   <html>
      <head>
         <title>{{ title }} </title>
      </head>

     <body>
      <p> welcome <?php echo $_SESSION['username']; ?>                                                                                                                                       
         <p> {{ body }} </p>
       <a href="http://localhost/slim/public_html/logout">logout</a>
     </body>
  </html>
Run Code Online (Sandbox Code Playgroud)

我无法获得该代码的会话用户名.

任何建议如何将会话传递给twig模板?

Mae*_*lyn 11

您应该将会话注册为全局树枝,因此可以在模板中访问它.

//$twig is a \Twig_Environment instance
$twig->addGlobal("session", $_SESSION);
Run Code Online (Sandbox Code Playgroud)

在您的模板中:

{{ session.username }}
Run Code Online (Sandbox Code Playgroud)