Search code examples
phpsymfonytemplatestwigbundles

Symfony2 Get Username in Navigation


I've started using Symfony2 Framework which looks very great for me. After creating the first bundles to rebuild an existing project with Symfony2 I came to this problem:

I've created a {% block navigation %} in base.html.twig, where my navigation is placed. Then, in my bundle, i'm extending the base.html.twig and the navigation is visible. Everything's fine.

My problem is that I want to show a greeting to logged in users, but the base.html.twig has no Logic or Container, and I'm wondering how I can "push" the user information so that I don't need to define the user information in the controller of every bundle.

At the moment, my controller action looks like this:

public function indexAction()
{
    $sUser = $this->getUser();
    return $this->render('@WhatEver/index.html.twig', array(
        'sUser'  => $sUser
    ));
}

So my question is: How can I manage my project so that the user information in the navigation exists from every bundle?

Is a Twig Extension the right way to go? Or do I need to change the way i'm including templates?

Thanks to everyone who can help me out with this!


Solution

  • The standard Symfony user can be accessed directly in Twig by using;

    {{ app.user.username }}