访问模板中的登录用户

我使用 FOSuserbundle 来开始用户注册 https://github.com/FriendsOfSymfony/FOSUserBundle

我已经登记好了。我现在要做的是获取登录用户的数据,并将其显示在我网站的每个页面上。就像“嗨,用户名”在标题类型的东西。

看起来在我的 App/Resources/views/base.html. twig中嵌入一个控制器是做这个 http://symfony.com/doc/current/book/templating.html#embedding-controllers的最好方法

因此,我编写了访问用户配置文件数据的控制器。我不知道如何访问嵌入式控制器中的 FOS 方法。因此,从我的 Acme/UserBundle/Controller/UserController.php我想这样做:

public function showAction()
{
$user = $this->container->get('security.context')->getToken()->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException(
'This user does not have access to this section.');
}


return $this->container->get('templating')
->renderResponse('FOSUserBundle:Profile:show.html.'.$this->container
->getParameter('fos_user.template.engine'), array('user' => $user));
}

我是从..: 厂商/bundle/FOS/UserBundle/Controller/ProfileController.php

114425 次浏览

You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

Warning, if the user is not logged, the app.user is null.

If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

So, in every of your pages you can do :

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

For symfony 2.6 and above we can use

\{\{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

\{\{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.