Passing Session to TWIG template

2020-02-29 15:58发布

i have a problem when i want to get $_SESSION['session']; in twig template using slim micro Framework.

this is my code :

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

i can't get session username with that code.

any suggestion how to passing session to twig template?

标签: php twig slim
4条回答
太酷不给撩
2楼-- · 2020-02-29 16:22

in php file:

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

in twig file:

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

You should pass the value from your PHP file into Twig via associative array.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-29 16:43

You should register session as a twig global, so it becomes accessible in your templates.

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

In your template:

{{ session.username }}
查看更多
家丑人穷心不美
4楼-- · 2020-02-29 16:43

I'm using Slim and Twig as well. My class:

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);
    }
}

As you can see I've added addGlobals. Now it works as it should and I can use {{session.user_id}} and so.

A part of my index.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();

I hope it will help you.

But is it safe to use 'global' in Twig ?

查看更多
放我归山
5楼-- · 2020-02-29 16:47

This how I was able to achieve it with Slim Framework ver3

$container['view'] = function ($container) {

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

    ...

    return $view;
};

And then access the session in the Twig template like

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

查看更多
登录 后发表回答