I'm trying to create a conditional twig function in a template I created for my website's home page (page--front.html.twig). Twig can supposedly do this out of the box, but I can't get this approach to work. The h1 is not being rendered, and no errors are being thrown. Here's the resource I used: http://enarion.net/news/2012/access-cookies-in-a-twig-template-using-symfony2/

In my template, I've added the following code:

{% if app.request.cookies.has('loader-activated') %}
    <h1>You have chosen your cookie brand!</h1>
{% endif %}

I'm using Cookie.js to declare my cookies. I've confirmed that it is working using a Chrome extension: enter image description here

Am I doing something wrong? I'm not strictly a developer, and have very limited abilities with Drupal 8 templating, so I'm sure it's something pretty obvious. If app.request.cookies isn't the best approach, what else should I use? I'd prefer that it is something simple, if possible!

  • Is {{ dump(app.request.cookies) }} or {{ app.request.cookies.get('loader-activated') }} returning anything?
    – leymannx
    Mar 12, 2019 at 17:56
  • 1
    Possible duplicate of How to correctly use cookies? (Twig and cache context)
    – leymannx
    Mar 12, 2019 at 17:57
  • @leymannx Neither return anything. I've looked at that post, but it's not very straight forward for me.
    – Kellen
    Mar 12, 2019 at 18:07
  • 3
    Thats because that is a symfony application construct, they will be empty because Drupal does not have those.
    – Kevin
    Mar 12, 2019 at 18:16
  • That means the other answer may be the way to go. Read cookies with PHP in a preprocess function and pass the value to Twig. But then you still need to find a way to bust the cache somehow.
    – leymannx
    Mar 12, 2019 at 18:30


Your Answer

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

Browse other questions tagged or ask your own question.