Hi all,

It seems that I'm struggeling with understanding the PHP caching :-)

Here's another example of my code where the drupal caching is 'bullying' me:

I'm developing a theme where the content of the site is depending on a regional choice. There can be 5 different regions but the differences are sometimes to little to create 5 different pages. So we decided to work with 5 fields on each page.
When the user visites the site for the first time, he will be redirected to a page where he has to choice his region. That choice is written in a cookie. The content of each node wil then depend on that cookie.

I have a preprocess function in my theme file where i define a variable to choose in the twig file:

function regio_test_preprocess_node(&$variables) {
    $variables['#cache']['contexts'][] = 'cookies'; 

    if($_COOKIE['RegioCookie'] == null){
        //redirect to choice page
    }

    $variables['regio_cookie_value'] = $_COOKIE['RegioCookie'];           
}

twig file (logic for only 2 regions):

{% if regio_cookie_value == 304 %}    
  {{ content|without('field_body_309')}}
{% elseif regio_cookie_value == 309 %}
  {{ content|without('field_body_304')}}           
{% endif %}

My Problem: When I change the value of my cookie, the content of my page doesn't change, unless I perform a cache clear. So i guess this is a caching problem...

I added this line of code, but didn't help me...

$variables['#cache']['contexts'][] = 'cookies'; 

Any help would be appreciated.

Kind regards,
Frederik

Comments

FreMun’s picture

Hi all,

I found the solution: the cache context was the way to go, but i needed to add the name of the cookie:

$variables['#cache']['contexts'][] = 'cookies:RegioCookie';

Hope this can be useful for somebody.

Kind regards,
Frederik

FreMun’s picture

Hi all,

I forgot to share this useful link about cache context: Cache contexts

Kind regards,
Frederik

aerrasti’s picture

Hi Frederik,

I have the same problem with the cookie context. I tried using the next code in the hook_preprocess:

    function hook_preprocess(&$variables, $hook) {
        if ( $hook == 'page') {
          $variables['cookie_name'] = $_COOKIE['cookie_name'];
          $variables['#cache']['contexts'][] = 'cookies:cookie_name';
        }
    }

After that, in the twig template, we apply some logic depending on the value of the cookie :

page.html.twig

    {% if cookie_name == 'logic1' %}
      <h1>logic1</h1>
    {% else %}
      <h1>logic2</h1>
    {% endif %}

The problem is that its not working for anonymous users.

I will appreciate any help :)

Thank you!

FreMun’s picture

Hi aerrasti,

As you can see here, we had the same problem when testing with anonymous users.

We used this to solve the problem, because we had to move on to production, but we are still working on a proper solution:

\Drupal::service('page_cache_kill_switch')->trigger();

Kind regards,
Frederik