0

Symfony 4 app using the FOSUserBundle.

I have made custom sub routes for the user profile (eg. profile/bookings), and I have added some custom fields to the user entity (firstName and lastName).

If I reference {{ user.firstName }} in my twig template on a custom route (non FOSUserBundle route), I get a 'User entity not found' error.

How do I access the properties of the user in the twig template?

TimothyAURA
  • 1,329
  • 5
  • 21
  • 44

1 Answers1

1

When you are rendering your view, from your controller, you can pass datas to the twig template using an array in the second parameter of the render() method.

This array is used this way : array('TwigVariableName' => $someValue, 'AnotherTwigVariable' => $someOtherValue)

In example :

//This is a controller
public function bookings()
{
    //get the current user
    $user = $this->get('security.token_storage')
                 ->getToken()
                 ->getUser();

    //Or, simplier, since we are in a controller :
    $user = $this->getUser();

    return ($this->render('bookings.html.twig', array('user' => $user)));
}

Or

As stated Cerad in comments, you can directly access in Twig the current user, using {{ app.user.firstName }}

Cid
  • 14,968
  • 4
  • 30
  • 45
  • Ok so how do I get the user? do I typehint User into the bookings() method? do i use a constructor? – TimothyAURA Dec 05 '18 at 04:50
  • Which user is it? The current one? – Cid Dec 05 '18 at 07:58
  • 2
    if it's current user (logged in user) you can access it whithin controller via `$this->getUser()`. Outside a controller you'll have to inject the `Security` service `$this->security->getUser()` – Etshy Dec 07 '18 at 10:30
  • Yes app.user.firstName worked, just wondering if this only works for User entity or other entities in the doctrine database as well? – TimothyAURA Dec 17 '18 at 12:57
  • You need to send datas in the view like I did in the first example. – Cid Dec 17 '18 at 13:01