问题
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?
回答1:
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 %}
来源:https://stackoverflow.com/questions/26524159/how-to-pass-user-informations-to-a-template-using-symfony2-and-fosuserbundle