I would like to let pages continue to benefit from Drupal 8 caching mechanism for anonymous users, except for a specific blocks which should update on every page refresh knowing that they are generated from Views.
Is it technically possible? How?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI would like to let pages continue to benefit from Drupal 8 caching mechanism for anonymous users, except for a specific blocks which should update on every page refresh knowing that they are generated from Views.
Is it technically possible? How?
What does that views block show?
D8 has cache tags and contexts that will automatically invalidate the block if something changes.
So if you have a list of nodes, every time a node is added or updated, that block will be updated, but until then, the cached version is used. Which is much better than rebuilding on every page.
It also works with the page cache, those pages will be updated automatically as well.
Many, many things just work with caching out of the box, without the need for any manual configurations.
Edit (responding to comment):
Random with the random sort plugin? That should automatically mark that block as non-cacheable. That however does not affect the page cache module. There is now a new smartcache/dynamic page cache module but it will only be in the next beta (or RC!). That will eventually allow to cache the rest of the page and just build that part.
But a case like this is probably best implemented by using some javascript. If there only a few nodes you could display them all, hidden by default and just randomly make one of them visible. Or request a URL with javascript that returns a random Ad or even better visit a random of N URL's that each returns an ad (e.g. by returning a list of URL's and then picking one of them. You could even do that directly for the image URL.
If this is a custom block, then you can use the Cache API, and set the cache max age to 0, eg
$build = [
// ...
'#cache' => [
'max-age' => 0,
],
];
If it is an existing block, then you can alter it to add this into the render array.