Accessing _SESSION variable in TWIG

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

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

Add this to your session middleware to change the values.

Pseudo session middleware example:

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:

Current user ID: {{ user.id }}

Read more Twig Global Variables

2 Likes