How to stop a specific block from being cached in Drupal 8

You are here

If you have a block in Drupal 8 that needs to update its contents every time there is a page load then use the hook and code below.

On a Drupal 8 website we developed, it needed to swap out different menus depending on the page that was being requested. We found that Drupal was caching the block twig logic and the only way we could get the menus to swap was keep clearing the cache. To stop this from happening we added ['max-age'] = 0 to the right part of the block render array and all the caching on the block type stopped.

 * Implements hook_preprocess_HOOK() for block.html.twig.
function template-name_preprocess_block(&$vars) {
  if($vars['derivative_plugin_id'] == 'add-block-id-name') {
    //-- This stops the block being cache in drupal 8
    $vars['#cache']['max-age'] = 0;