web-dev-qa-db-ja.com

テンプレートでログインしているユーザーにアクセスする

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));
}

取得元:vendor/bundles/FOS/UserBundle/Controller/ProfileController.php

92
ed209

コントローラーで何も要求しなくても、twigテンプレートでユーザーデータに直接アクセスできます。ユーザーは次のようにアクセスできます:app.user

これで、ユーザーのすべてのプロパティにアクセスできます。たとえば、次のようなユーザー名にアクセスできます:app.user.username

警告、ユーザーがログインしていない場合、app.userはnullです。

ユーザーがログインしているかどうかを確認する場合は、is_granted twig関数を使用できます。たとえば、ユーザーがROLE_ADMINを持っているかどうかを確認したい場合は、is_granted("ROLE_ADMIN")を実行するだけです。

だから、あなたのすべてのページであなたができる:

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

Symfony 2.6以降では以下を使用できます

{{ app.user.getFirstname() }}

asapp.securityTwigテンプレートのグローバル変数は廃止され、廃止予定3.0から削除される

詳細:

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

そして、グローバル変数を参照してください

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

13
Hahn