将会话传递到 TWIG 模板


Passing Session to TWIG template

当我想使用纤薄的微框架在 twig 模板中获取$_SESSION['session'];时,我遇到了问题。

这是我的代码:

<!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>

我无法使用该代码获取会话用户名。

任何建议如何将会话传递到树枝模板?

您应该将会话注册为 twig 全局,以便在模板中可以访问它。

//$twig is a 'Twig_Environment instance
$twig->addGlobal("session", $_SESSION);

在您的模板中:

{{ session.username }}

我也在使用Slim和Twig。 我的班级:

class twigView extends Slim_View {
    public function render( $template) {
        $loader = new Twig_Loader_Filesystem($this->getTemplatesDirectory());
        $twig = new Twig_Environment($loader);
        $twig->addGlobal("session", $_SESSION);
                return $twig->render($template, $this->data);
    }
}

如您所见,我已经添加了addGlobals.现在它可以正常工作,我可以{{session.user_id}}等使用。

我的索引的一部分.php:

    require './lib/twigView_class.php';
    require_once './lib/Twig/Autoloader.php';
    require './lib/Paris/idiorm.php';
    require './lib/Paris/paris.php';
    Twig_Autoloader::register();

我希望它能帮助你。

但是在 Twig 中使用"全局"安全吗?

这就是

我能够使用 Slim Framework ver3 实现它的方式

$container['view'] = function ($container) {
    ...
    $view = new Twig($settings['view']['template_path'], $settings['view']['twig']);
    $view->getEnvironment()->addGlobal('session', $_SESSION);
    ...
    return $view;
};

然后在 Twig 模板中访问会话,例如

<a href="#" class="dropdown-toggle" data-toggle="dropdown">
  <img src="#" class="img-circle">&nbsp;{{ session.username }}<b class="caret"></b>
</a>

在 php 文件中:

$app->get('/your_route_here', function() use ($app) {
$app->render('view_for_route.twig', array('session_username' => $_SESSION['username']) );});

在树枝文件中:

<p> welcome {{ session_username }} </p> 

您应该通过关联数组将 PHP 文件中的值传递到 Twig 中。