0

I have a region with menus, a menus displays depending on the url example if on the about page(sitename/about-us), display about menu and links as a sub menu.

It works, but the problem is after navigating through the site a couple of times, the region caches. is the anyway i can clear the regions cache on page reload.

I tried the below in my .theme

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

    }
  }

also tried

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

not sure what steps I can follow to achieve the above

1
  • This sounds better suited for Menu Block module as it accounts for this.
    – Kevin
    Jan 17, 2019 at 13:07

1 Answer 1

-1

Add code below:

class MYCUSTOMBLOCK extends BlockBase {
  public function build() {
    return array(
      '#markup' => '', // the content of your block
    );
  }
  public function getCacheMaxAge() {
   return 0; // No caching gets applied here
  }
}
3
  • Hi Stef not sure why this comment was down voted, could you possibly explain
    – Lloyd_07
    Jan 18, 2019 at 7:18
  • Hi @Lloyd_07: try to load in the menu's in the '#markup' section. Then, place this custom block in your region. The getCacheMaxAge() function should make sure this block is not cached. Jan 18, 2019 at 9:21
  • I don't see how this answer addresses the problem. The issue is that the region is being cached, not the block. So the region will clear out regardless of whether the block is cached.
    – AlxVallejo
    Sep 21, 2020 at 16:38

Your Answer

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

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