In my custom page.html.twig I have a variable that adds an alert bar to the page if the user is expired. This is based on a custom user field.
It's generated here in my custom_theme.theme file like so.
function custom_theme_preprocess_page(&$variables){
$uid = \Drupal::currentUser()->id();
$current_user = \Drupal\user\Entity\User::load($uid);
$now =strtotime('now');
$paidThrough = strtotime($current_user->field_expiration_date->value);
if($paidThrough < $now){
$variables['alert'] = 'Your account has expired';
}
$variables['#cache'] = [
'max-age' => 0,
'contexts' => ['url.path']
];
}
and then inside my page.html.twig file I have
<div class="alert">{{ alert }}</div>
<div class="main">{{ page.content }}</div>
Even though some users have been updated to no longer see the alert, they still see it on the home page. If they click around to different pages they no longer see the report, but on the home page they always see it. I'm guessing they no longer see it on other pages because those pages were not cached for them. Also I'm using the page manager and panels plugins for many of these pages including the home page.
Why would twig variables be cached for authenticated users? Is there a way to prevent twig variables from being cached?
I did see a similar post here Twig/Drupal caching and dynamic variables But I'm not sure how that would work or how to implement that.
UPDATE: It was mentioned that using $variables['#cache']['contexts'][] = 'url'; would be problematic but if this is a dynamic alert box that appears on every page wouldn't that be necessary?
UPDATE 2: Actually it occurred to me that I'm already using
$variables['#cache']['contexts'][] = 'url';
in my own way here
$variables['#cache'] = [
'max-age' => 0,
'contexts' => ['url.path']
];
But that didn't seem to resolve the issue. Unless 'url' and 'url.path' makes a difference.