Accessing the logged user in a Twig template

Published on 2021-03-27 • Modified on 2021-03-27

In this snippet, we will see how to access the logged user in a Twig template. This can be you through the app Twig global variable. You can test if the app.user variable is null but you can also use the rights helpers which is a better practice.


{% if app.user is null %}
    <h3>No user logged for now!</h3>
{% else %}
    <h3>Username {{ app.user.username }}</h3>
{% endif %}

<p>Or</p>

<h3>Username: {{ app.user.username ?? 'Anonymous user' }}</h3>

<p>Or</p>

{% if is_granted("ROLE_USER") %}
    <h3>Hi {{ app.user.username }}! Whow are you doing?</h3>
{% else %}
    <h3>ROLE_USER is not granted to the current user.</h3>
{% endif %}
HTML demo of the snippet

No user logged for now!

Or

Username: Anonymous user

Or

ROLE_USER is not granted to the current user.


 More on Stackoverflow   Read the doc  Random snippet

  Work with me!


Call to action

Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )

Thank you for reading! And see you soon on Strangebuzz! 😉

COil