Often you may need to know whether a user is logged in or not inside a template to show or not show something. For example you might want to show links to login or register if a user is not logged in but show a link to logout if the user is logged in.
To do this you use is_granted() within a template with one of the following.
IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_REMEMBERED, IS_AUTHENTICATED_FULLY
<div class="modal-body">
<ul class="nav flex-column">
{% if is_granted('ROLE_SUPER_ADMIN_1') %}
<a class="nav-link" href="{{ path('show_dash') }}">Dashboard</a>
{% endif %}
{% if is_granted('ROLE_USER') %}
<a class="nav-link" href="{{ path('app_logout') }}">Logout</a> {% else %}
<a class="nav-link" href="{{ path('app_login') }}">Login</a> or <a class="nav-link" href="{{ path('app_register') }}">Signup</a> {% endif %}
</ul>
</div>
Using ROLE_SUPER_ADMIN_1 which is something I made up for my own app to check what type of admin the user is. I don’t really like the IS_AUTHENTICATED_* methods, read more about them in the link below if you want.
Link to more information about IS_AUTHENTICATED_* here in a really old symfony cast I found via google.
Comments
2 responses to “Symfony 5+ check if user is logged in inside a twig template”
I love you…
[…] Symfony 5+ check if user is logged in inside a twig template […]
You must log in to post a comment.