W3docs

Accessing session from TWIG template

In a TWIG template, you can access the session data by using the app.session variable.

In a TWIG template, you can access session data using the app.request.session variable. (Note: app.session was deprecated in Symfony 4.3 and removed in 5.0+. Use app.request.session for modern Symfony versions.) The session object is an instance of Symfony\Component\HttpFoundation\Session\SessionInterface, which provides a variety of methods for working with session data.

Here are a few examples of how you might use the session variable in a TWIG template:

  • To access a value stored in the session under the key "username":
    {{ app.request.session.get('username') }}
  • To check if a session key exists:
    {{ app.request.session.has('key') }}
  • To add a key-value pair to the session:
    {{ app.request.session.set('key', 'value') }}
  • To remove a key-value pair from the session:
    {{ app.request.session.remove('key') }}
  • To get all session data:
    {{ app.request.session.all() }}

It is important to note that Twig templates are intended only for the presentation layer, and you should not use them for business logic. If you need to access session data or other variables specific to the current request, it is better to retrieve them in the controller and pass them to the template.