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!

Upvotes: 2

Views: 496

Answers (2)

Rooneyl
Rooneyl

Reputation: 7902

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

{{ app.user.username }}

Upvotes: 5

KhorneHoly
KhorneHoly

Reputation: 4766

You could set the UserName in the Session

Then you could call it with {{ session.username }}

Another possibility would be the FOS:UserBundle. If the User is logged in you could show it with {{ app.user.name }}.

A third option would be a Twig Extension

Upvotes: 1

Related Questions