Question

I am using the silex framework for my project. I am using the SecurityServiceProvider with a custom user implementation. The login/logout works and I am able to view the correct user information in the symfony profiler (stored as a session attribute). Now I am trying to add the custom user information to the twig environment so that is is accessible from the templates. Here is what I've come up with:

$app['twig'] = $app->share($app->extend('twig', function($twig, $app) {
    $token = $app['security']->getToken();
    $userInfo = null;
    if (null !== $token) {
        $userInfo = $token->getUser()->getTwigInfo();
    }
    $twig->addGlobal('userinfo', $userInfo);
    return $twig;
}));

I am trying to extend the environment and it works, however the user information seems to be processed later and my userinfo attribute is always null. I guess that I have to somehow extend the twig environment later but do not know exactly how to do that. Can someone help me?

Was it helpful?

Solution

Silex gives you access to the app instance directly from Twig.

So you could do:

{{ app.security.token ? app.security.token.user.twigInfo : null }}

or

{% set userinfo = app.security.token ? app.security.token.user.twigInfo : null %}

{{ userinfo }}

If you prefer to handle it within your PHP code, then you can create a new definition

$app['userinfo'] = $app->share(function($app) {
    $token = $app['security']->getToken();

    return (null !== $token) ? $token->getUser()->getTwigInfo() : null;
}));

Then in your Twig template

{{ app.userinfo }}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top