[symfony] 템플릿에서 로그인 한 사용자 액세스

사용자 등록을 시작하기 위해 FOSuserbundle을 사용하고 있습니다. https://github.com/FriendsOfSymfony/FOSUserBundle

등록 / 로그인 및 로그 아웃했습니다. 지금하고 싶은 것은 로그인 한 사용자 데이터를 가져와 내 사이트의 모든 페이지에 표시하는 것입니다. 헤더 유형의 “Hi username”처럼.

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



답변

컨트롤러에서 아무것도 요청하지 않고 twig 템플릿에서 직접 사용자 데이터에 액세스 할 수 있습니다. 사용자는 다음과 같이 액세스 할 수 있습니다 app.user.

이제 사용자의 모든 속성에 액세스 할 수 있습니다. 예를 들어 다음과 같은 사용자 이름에 액세스 할 수 있습니다 app.user.username.

경고, 사용자가 기록되지 않은 경우 app.user는 null입니다.

사용자가 로그인되어 있는지 확인하려면 is_grantedtwig 기능을 사용할 수 있습니다 . 예를 들어, 사용자가을 가지고 있는지 확인하려면 ROLE_ADMIN을 수행하면 is_granted("ROLE_ADMIN")됩니다.

따라서 모든 페이지에서 다음을 수행 할 수 있습니다.

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


답변

심포니 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


답변

{{ . 사용자 . 사용자 이름 | 기본값 ( '' ) }} 

예를 들어 로그인 사용자 이름을 제시하면 성가신 오류 메시지를 피하여 사용자가 로그인하지 않을 때 필터 함수 default ( ”)가 좋습니다.


답변