简体   繁体   中英

How to pass user informations to a template using Symfony2 and FosUserBundle

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?

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM