17

I'm trying to access cookies I set in my Drupal website. I created two cookies on a form submission :

  • with the Drupal funtion = user_cookie_save(['myfirstcookie' => 'myfirstdata'])
  • with the classic PHP function = setcookie('mysecondcookie', 'myseconddata', time() + (86400 * 30), "/")

My cookies are set, no problem. But, I didn't find how to get them (or one of them) from my Twig templates. The app.request.cookies of Symfony seems to not exist.

Do you have any idea ?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Dadaz
  • 171
  • 1
  • 1
  • 4

2 Answers2

61

Twig has the global app helper context, via which you can access the cookies (among other things). Try this:

{{ dump(app.request.cookies) }}

And ultimately:

{{ app.request.cookies.get('MY_COOKIE_NAME') }}

Remember, cookies is an instance of ParameterBag (API), so you have to access it via get() call.

Hope this helps...

Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85
0

Past Cookie variable from the controller and check it. It works to me. My code in controller is:

$data['cookie'] = $_COOKIE['postcode'];

postcode is my cookie name and in my twig templete, i write this line of code

{{  cookie  }}

and show my cookie value. Thanks.

Y. Joy Ch. Singha
  • 3,056
  • 24
  • 26