0

I'm using symfony2, I installed FosUserBundle and I created a bundle UserBundle as indicated in the FosUserBundle online docs. so far so good. I also created another controller and I'm able to access the logged user information in this way:

$user = $this->container->get('security.context')->getToken()->getUser();

now imagine that in my website, for all the pages/controller, I need to display some user information, even a simple "Welcome MyUser" at the top of the page (so in base.html.twig). I don't want to replicate the line above in all the controllers, so where is the best place to get this information once and pass them to the base template?

user3174311
  • 1,714
  • 5
  • 28
  • 66

1 Answers1

0

For the example you gave, "Welcome MyUser" , you can get this var in twig template with

 {% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

This is, if you don't need logic

Also if you didn't knew it you can use heritage in twig, so that you can create a navbar.html.twig with this fosuser var in it, and then in all your templates do

{% extends "AcmeMyBundle::navbar.html.twig" %}
{% block body %}
   ....
{% endblock %}
oligan
  • 634
  • 6
  • 18
  • good thanks. what's if I need logic? for example, if in the same place I'd need to display the number of unread email... – user3174311 Oct 23 '14 at 08:45
  • Ha. then you're in the same case as me. I created a service for it, but I still need to call the service in every controller, since you can't do controller heritage, but only template heritage. I'd happy to hear a solution though, but imo not possible. – oligan Oct 23 '14 at 08:47
  • A trick you could do is store the number of unread email in user entity, and then in twig do {{ app.user.unreadEmail }} – oligan Oct 23 '14 at 08:51