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

一笑奈何 提交于 2019-12-12 03:18:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!