在模板中访问已login的用户

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

我已经注册/login和注销。 我现在要做的是抓取login的用户数据,并将其显示在我的网站的每个页面上。 像“Hi用户名”的标题types的东西。

这似乎是embedded一个控制器在我的应用程序/资源/ views / base.html.twig是最好的方式来做到这一点http://symfony.com/doc/current/book/templating.html#embedding-controllers

所以我写了我的控制器来访问用户configuration文件数据。 我想不出的是如何在我的embedded式控制器中访问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)); } 

我从抢:vendor / bundles / FOS / UserBundle / Controller / ProfileController.php

您可以直接访问树枝模板中的用户数据,而无需在控制器中请求任何内容。 用户可以这样访问: app.user

现在,您可以访问用户的每个属性。 例如,您可以像访问这样的用户名: app.user.username

警告,如果用户没有logging, app.user是空的。

如果你想检查用户是否login,你可以使用is_granted函数。 例如,如果你想检查用户是否有ROLE_ADMIN ,你只需要做is_granted("ROLE_ADMIN")

所以,在你的每一页你可以做:

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

对于symfony 2.6及以上版本,我们可以使用

 {{ app.user.getFirstname() }} 

作为用于Twig模板的app.security全局variables已被弃用,并将从3.0中删除

更多信息:

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

并看到全局variables

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

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

只是提供login用户名,例如,过滤function默认('')应该很好,当用户不login,只是避免恼人的错误信息。