Accessing session from TWIG template

In a TWIG template, you can access the session data by using the app.session variable. The app.session variable is an instance of Symfony\Component\HttpFoundation\Session\Session, which provides a variety of methods for working with session data.

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

  • To access a value stored in the session under the key "username", you would use app.session.get('username'). This will return the value associated with the "username" key, or null if the key does not exist.

  • To check if a session key exist, you can use app.session.has('key'). This will return true if the key exists in the session, and false otherwise.

  • To add a key-value pair to the session, you can use app.session.set('key', 'value').

  • To remove a key-value pair from the session, you can use app.session.remove('key').

  • To get all session data, you can use app.session.all()

Watch a course Learn object oriented PHP

It is important to note that, TWIG template is only for presentation layer and you should not use it for any business logic. If you need to access session or other variables that are specific to the current request, it's better to use controller and pass those variables to the template.