# Accessing \_SESSION variable in TWIG

**URL:** <https://discourse.slimframework.com/t/accessing-session-variable-in-twig/4232>\
**Category:** Questions\
**Created:** [June 19, 2020, 5:08pm UTC](https://discourse.slimframework.com/t/accessing-session-variable-in-twig/4232 "2020-06-19T17:08:00Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![odan](https://avatars.discourse-cdn.com/v4/letter/o/9de053/32.png) [@odan](https://discourse.slimframework.com/u/odan)\
**Post date:** [June 21, 2020, 4:22pm UTC](https://discourse.slimframework.com/t/accessing-session-variable-in-twig/4232/10 "2020-06-21T16:22:45Z")

</div>

From MVC perspective the question should be: “How to pass (session) data to the view layer?”

It wouldn’t work to register the session data inside the container because it is too early. Usually a middleware starts the session handler a bit later. So within the container definition, the session would be empty.

If you try to register a global twig variable within a middleware, you may get an error message like this:

`Unable to add global "session" as the runtime or the extensions have already been initialize`.

The reason is that after the initialization of Twig, the global variables are “locked” and can only be read.

But there is a trick.

When using objects, it is possible to change the value of the global variable afterwards. It is still not possible to replace the object itself, but it is possible to change the property values of the object.

**Example**

```php
$environment = $twig->getEnvironment();
$environment->addGlobal('user', (object)[
    'id' => null,
]);

```

Add this to your session middleware to change the values.

**Pseudo session middleware example:**

```php
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    // Start session
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start()
    }

    $user = $this->twig->getEnvironment()->getGlobals()['user'];

    // Set global twig variables
    $user->id= $_SESSION['id'] ?? null;
       
    return $handler->handle($request);
}

```

In twig:

```auto
Current user ID: {{ user.id }}

```

Read more [Twig Global Variables](https://odan.github.io/2020/04/17/slim4-twig-templates.html#global-variables)

---

_[View the full topic](https://discourse.slimframework.com/t/accessing-session-variable-in-twig/4232)._
