如何使用Symfony2和FosUserBundle将用户信息传递给一个模板[英] How to pass user informations to a template using Symfony2 and FosUserBundle

本文是小编为大家收集整理的关于如何使用Symfony2和FosUserBundle将用户信息传递给一个模板的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在使用symfony2,我安装了fosuserbundle,并创建了一个捆绑包用户,如fosuserbundle在线文档中所示.到目前为止,一切都很好. 我还创建了另一个控制器,并且能够以这种方式访问​​已记录的用户信息:

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

现在可以想象,在我的网站中,对于所有页面/控制器,我需要在页面顶部显示一些用户信息,甚至在页面顶部(So base.html.twig).我不想在所有控制器中复制上面的行,因此,获取此信息并将其传递到基本模板的最佳位置是哪里?

推荐答案

对于您给出的示例" Welcome Myuser",您可以使用

在树枝模板中获得此var
 {% if is_granted("ROLE") %}
    Hi {{ app.user.username }}
{% endif %}

这是,如果您不需要逻辑

另外,如果您不知道它可以在树枝中使用遗产,以便在其中使用此fosuser var创建一个navbar.html.twig,然后在所有模板中都可以

在其中创建navbar.html.twig
{% extends "AcmeMyBundle::navbar.html.twig" %}
{% block body %}
   ....
{% endblock %}

本文地址:https://www.itbaoku.cn/post/2090841.html

问题描述

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