2011-09-18 55 views
80

我使用FOSuserbundle上手的用戶註冊https://github.com/FriendsOfSymfony/FOSUserBundle訪問登錄的用戶在模板

我知道了註冊/登錄和註銷。我現在要做的是抓取登錄的用戶數據並將其顯示在我網站的每個頁面上。像「Hi用戶名」在標題類型的東西。

好像在我應用程序/資源/視圖/ base.html.twig嵌入控制器做到這一點http://symfony.com/doc/current/book/templating.html#embedding-controllers

所以我寫了我的控制器來訪問用戶配置文件數據的最佳方式。我想不出的是如何在我的嵌入式控制器中訪問FOS方法。所以從我的阿克米/ UserBundle /控制器/ 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)); 
} 

這是我從抓起: 供應商/包/ FOS/UserBundle /控制器/ ProfileController.php

回答

205

您可以直接在樹枝模板中訪問用戶數據,而無需在控制器中請求任何內容。用戶可以這樣訪問:app.user

現在,您可以訪問用戶的每個屬性。例如,您可以訪問如下用戶名:app.user.username

警告,如果用戶未登錄,app.user爲空。

如果你想檢查用戶是否登錄,你可以使用is_granted枝功能。例如,如果你想檢查用戶是否有ROLE_ADMIN,你只需要做is_granted("ROLE_ADMIN")

所以,在每一個頁面,你可以這樣做:

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

謝謝。我實際上已將「ROLE」更改爲「IS_AUTHENTICATED_REMEMBERED」,並且效果很好。 – ed209

+5

我沒有使用FOSuserbundle(除非它現在帶有),但'app.user.username'仍然適用於我。可能對有人知道有用。 –

+0

謝謝!在文檔中這應該更清晰。 –

12

爲symfony1.2 2.6及以上,我們可以使用

{{ app.user.getFirstname() }} 

app.security的枝條模板全局變量已棄用,將從3.0中刪除

更多信息:

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

並查看

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

+4

不必要的方法調用。您可以使用像這個'{{app.user.firstname}}'這樣的動態屬性。我猜想它更符合前端開發。 – kacper3w

+2

儘管我同意上面關於不必要的評論,但我會對此表示贊同,因爲它表明如果需要,可以使用自定義方法 – Simon

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

就目前的登錄用戶名,例如,過濾功能默認(「」)的全局變量應該是不錯的,當用戶沒有通過登錄避免煩人的錯誤信息。

+2

以及它如何解決問題?也許你需要添加解釋 –

相關問題