I'm working on a project based on Drupal 8.3.x . It comes with cache already enabled which is great if we know how to customize it. I've been going through the different tutorials and I was able to implement the following cache for my custom block:
$build = [
'#cache' => [
'tags'=>['node'], // Invalidate cache whenever a new node is created/modified/deleted
'contexts'=>['url'] // Invalidate cache per url
]
];
The problem I'm having is my website depends on cities and display different content for different cities. I have the following scenarios:
- When I visit www.example.com/city1 the block should display nodes from city 1
- When I visit www.example.com/city2 the block should display nodes from city 2
- When I visit www.example.com the block should display the nodes from the latest visited city
With the snippet above I'm able to make the point 1 and 2 work. however when visiting front
only the content of the first visited city appears, which make sense because the Invalidation of the cache depends on the url and is only 1 url.
I tried this but didn't work:
global $selected_city;
'#cache' => [
'keys'=>['home_slider_'.$selected_city],
'tags'=>['node'],
'contexts'=>['url']
]
Where $selected_city
is coming from the cookie or the request depending on separate logic.
Is there a way to Invalidate the cache per url + global variable ?
EDIT: The answer below fixes the issue for authenticated users but doesn't fix it for anonymous users. Any help with that would be appreciated.