4
votes

I'm using Twig in a silex application. In a pre request hook I'd like to check if a user is logged in and if they are add the user object to Twig (so I can render logged in / logged out state in the menu).

However having looked at the source code it looks like it's only possible to supply template view variables as an argument to the render method. Am I missing something here?

Here is exactly what I'd like to achieve:

// Code run on every request    

$app->before(function (Request $request) use ($app)
{
    // Check if the user is logged in and if they are
    // Add the user object to the view

    $status = $app['userService']->isUserLoggedIn();

    if($status)
    {
        $user = $app['userService']->getLoggedInUser();

        //@todo - find a way to add this object to the view 
        // without rendering it straight away
    }

});
4

4 Answers

18
votes
$app["twig"]->addGlobal("user", $user);
16
votes

In addition to what Maerlyn said, you can do this:

$app['user'] = $user;

And in your template use:

{{ app.user }}
1
votes

you can use twig->offsetSet(key, value) to pre render values

example when registering twig helper

$container['view'] = function ($c) {
    $view = new \Slim\Views\Twig('.templatePath/');

    // Instantiate and add Slim specific extension
    $basePath = rtrim(str_ireplace('index.php', '', $c['request']->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($c['router'], $basePath));

    //array for pre render variables
    $yourPreRenderedVariables = array(
       'HEADER_TITLE' => 'Your site title',
       'USER'  => 'JOHN DOE'
    );
    //this will work for all routes / templates you don't have to define again
    foreach($yourPreRenderedVariables as $key => $value){
        $view->offsetSet($key, $value);
    }

    return $view; 
};

you can use it on template like this

<title>{{ HEADER_TITLE }}</title>
hello {{ USER }},
0
votes

The answer provided by Maerlyn is wrong, as there is no need to use addGlobal, as the user object already exists in the environment global variable in twig as the documentation says:

Global Variable

When the Twig bridge is available, the global variable refers to an instance of App Variable. It gives access to the following methods:

{# The current Request #}
{{ global.request }}

{# The current User (when security is enabled) #}
{{ global.user }}

{# The current Session #}
{{ global.session }}

{# The debug flag #}
{{ global.debug }}

Aso according to the documentation, if you want to add any other global called foo for example, you should do:

$app->extend('twig', function($twig, $app) {
    $twig->addGlobal('foo', 127);                    // foo = 127
    return $twig;
});

After registering the twig service.

Registering the twig service is as simple as:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/views',
));