1

I have a little issue regarding my custom block module. The module itself fetches weather data via json-request and the data is shown as a 4-day weather forecast to the user. As the weather should be actualized every day I want to set a "maximum cache time" or even disable caching for the whole block. Right now I would have to flush the cash manually every day.

After a little bit of research to that topic I found out that using 'max-age' in the build() function would do the trick but it does not affect the caching for anonymous users at all.

Using \Drupal::service('page_cache_kill_switch')->trigger(); would disable the cache for a specific page or content-type but I don't want to disable the caching for a whole page at once.

So how can I trigger the caching for my custom-block? Or is there even a way to disable the caching for a certain part of the code e.g. the json-request in my case?

1
  • 1
    You can use lazy builder or fetch data in js.
    – user21641
    Commented Sep 2, 2017 at 15:00

2 Answers 2

2

This is a known issue Bubbling of elements' max-age to the page's headers and the page cache.

The Internal Page Cache is designed for database content, which is handled by cache tags. So a workaround would be to add a custom cache tag to the block

$build['#cache']['tags'][] = 'weather_forecast';

which will bubble up to the page level and so you can invalidate both cached items, block and page, in a cron job:

/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  \Drupal\Core\Cache\Cache::invalidateTags(['weather_forecast']);
}

All credit goes to @Berdir: Cache max-age and varnish ESI

1
  • Thank you. That did the job for me! In my case i had to declare the custom cache tag with '#cache' => [ 'tags' => ['weather_forecast'], ], to get it to work.
    – tinytree
    Commented Sep 2, 2017 at 21:26
0

Limitations of max-age

Unfortunately, max-age does not work for anonymous users and the Drupal core Page Cache module. For example, see these issues:

Until these (and perhaps other) issues are resolved, beware that setting max-age on a render array included in a page is insufficient to ensure that anonymous users will see a new version after the max-age as elapsed. In the meanwhile, the Cache Control Override contributed module tries to mitigate the problems. You might also have more luck setting a custom cache tag on pages with time-dependent content and invalidating those cache tags manually via hook_cron(). Good luck!

Source: https://www.drupal.org/docs/drupal-apis/cache-api/cache-max-age#s-limitations-of-max-age

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.