Search code examples
phpsymfonytwigtoken

Symfony 3 - How to recover and process an object in twig?


on my site it is possible to authenticate thanks to a CAS authentication. Then a search is performed in the database to retrieve the corresponding User object (with all of its attributes). This User object is then placed in the token.

Arrived on the profile page of the user (twig), I wish I could at the very beginning get the user object from the token to then use it such as "user.mail", "user.name", rather than having to go through the token all the time.

I know I could possibly get this User object from the controller and pass it as a parameter to my twig function to be able to use it, but I would still like to know if what I ask is feasible...

In twig, I know that I can use this :

(app.getToken().getAttribute('user')) 

But I would like a thing like :

{% $user = (app.getToken().getAttribute('user')) %}
//some code
{% Name : user.name %}

Thanks !


Solution

  • Use:

    {% set user = app.getToken().getAttribute('user') %}

    see twig doc on how to declare variables:

    https://twig.symfony.com/doc/2.x/tags/set.html