2

This question was already asked a few years ago, and the way of doing it was through a plugin. I was wondering if there is a way of doing it just using Craft and Twig.

I set up a cookie using JavaScript, and I want to read it with Craft. Is this possible?

2 Answers 2

3

Assuming this is for Craft 3, you can do something like this from a template to loop through all available cookies for a site:

{% set cookies = craft.app.request.getCookies() %}

{% for cookie in cookies %}
    {{ cookie.name }}
{% endfor %}
2
  • That seems to work, but I get back 'CRAFT_CSRF_TOKEN'. I am expecting another value. {% set cookies = craft.app.request.getCookies('invited') %} I'm requesting the cookie like that.
    – JSosa
    Jun 25, 2019 at 15:59
  • 1
    @JSosa getCookies() returns the collection of cookies. The cookie you want would be cookies['invited'] out of the returned set. Reference: yiiframework.com/doc/api/2.0/…
    – cherrykoda
    Jan 17 at 23:12
2

If you want a specific cookie instead of the set of cookies, you'd use

Old Craft 3 Syntax:

{% set specificCookie = craft.app.request.getCookie('specificCookie') %}

Deprecation Replacement (for Craft 4 compatibility):

craft.app.request.cookies.get('specificCookie')

Craft 3 Docs: https://docs.craftcms.com/api/v3/craft-web-twig-variables-request.html#method-getcookie

Codebase Reference: https://github.com/craftcms/cms/blob/v3/src/web/twig/variables/Request.php#L212-L217

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.