I'm building a Drupal 8 site that has a stock quote on every page. The data for the quote comes from a database. The requirement is that the stock quote data be refreshed every five minutes and I've nailed down the database update portion of the process.

The other content on each page is highly static and I do not want to refresh the cache every five minutes. Our Drupal config has cache set at one hour. We also have Varnish to deal with.

Is it possible to exclude just this one block from cache? I've tried using the preprocess hook to set max-age:

function mytheme_preprocess_block(&$vars) {
    if($vars['derivative_plugin_id'] == 'stocktickerblock') {
        $vars['#cache']['max-age'] = 0;

But this doesn't seem to work.

Thank you

  • is the block from your own custom plugin ? or is it from contrib ?
    – taggartJ
    Feb 1 '18 at 4:27
  • This is our own custom plugin. I will try your suggestion below and report back. Thanks!
    – pburgh
    Feb 1 '18 at 12:08

Put this in a custom module:

 * Implements hook_block_view_alter().
function MYMODULE_block_view_alter(array &$build, Drupal\Core\Block\BlockPluginInterface $block) {
  if (!empty($build['#id']) && $build['#id'] == 'stocktickerblock') {
    $build['#cache']['max-age'] = 0;

but if the your 'stocktickerblock' block is from a custom plugin you can set the build cache directly in that plugin render array.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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