Accessing the logged-in user in a template

前端 未结 3 2002
陌清茗
陌清茗 2020-12-12 12:54

I\'m using FOSuserbundle to get started with User registration https://github.com/FriendsOfSymfony/FOSUserBundle

I\'ve got it registering / logging in and out. What

相关标签:
3条回答
  • 2020-12-12 13:19
    {{ app.user.username|default('') }}

    Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

    0 讨论(0)
  • 2020-12-12 13:25

    You can access user data directly in the twig template without requesting anything in the controller. The user is accessible like that : app.user.

    Now, you can access every property of the user. For example, you can access the username like that : app.user.username.

    Warning, if the user is not logged, the app.user is null.

    If you want to check if the user is logged, you can use the is_granted twig function. For example, if you want to check if the user has ROLE_ADMIN, you just have to do is_granted("ROLE_ADMIN").

    So, in every of your pages you can do :

    {% if is_granted("ROLE") %}
        Hi {{ app.user.username }}
    {% endif %}
    
    0 讨论(0)
  • 2020-12-12 13:26

    For symfony 2.6 and above we can use

    {{ app.user.getFirstname() }}
    

    as app.security global variable for Twig template has been deprecated and will be removed from 3.0

    more info:

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

    and see the global variables in

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

    0 讨论(0)
提交回复
热议问题