Access cookies in a twig template using Symfony2

Ever wanted to easily access a cookie in a twig template using Symfony2? It’s really easy and usable out of the box.
You might already know that the global twig variable app contains various information about the user, the current session and the current locale/language of the user. Check this stackoverflow page for a handy list.

The cookies are stored in the app.request object. You can access them easily with

{% app.request.cookies %}

There you’ll find an instance of the ParameterBag class (at least in Symfony 2.0). This provides some nice functions as e.g. the has() method.

Checking if a cookie is set can be used inside an if statement:

{% if app.request.cookies.has('best_cookies_with_swiss_chocolate') %}
You have chosen your cookie brand!
{% endif %}

That’s it.


If you would like to combine this with a little front-end code using e.g. jQuery and the jQuery cookie plugin written by Klaus Hartl, you could set the cookie with

<script type="text/javascript">
$.cookie('best_cookies_with_swiss_chocolate', 'Lindt');
</script>