0

My question is how can I access the logged in user from the view? I know it's possible with twigs {app.user}, but I have to do it in php template. Is it possible to get the user from php template? Something like $app->getUser() or something?

2 Answers 2

1

You can access the user through the security.context service. For example, you could write in your controller:

$User = null;
$securityToken = $this->container->get('security.context')->getToken();

if (is_object($securityToken) && is_callable([$securityToken, 'getUser']))
    $User = $securityToken->getUser();

Note: It is possible that the $User variable does not really contain your user entity. In this case, you should additionally check that $User is an instance of your user entity:

… && is_object($User) && is_callable([$User, 'getId']) && $User->getId() …
Sign up to request clarification or add additional context in comments.

Comments

0

To allow the user to log in using Twig templates magic method {{ app.user.username }}

1 Comment

Yes, I understand, but I use php templating. Whatever, It turned out, I can access the service container from the view too, so I can call for the $user = $this->container->get('security.context')->getToken()->getUser() methods, that returns the user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.