0

I have a custom block, it displays in every pages with dynamic data calculates in every refresh, How can I disable cache for this block for anonymous users?

I try with:

public function build() {
  return [
    '#markup' => time(),
    '#cache' => [
      'max-age' => 0,
    ],
  ];
}

It won't work.

Edit: I don't want to disable the cache for the entire page, I just need a specific block not to be cache.

2

1 Answer 1

0

If you want to completely disable caching for the block, use this function in your block class:

  public function getCacheMaxAge() {
    return 0;
  }

I've never found in the documentation why

'#cache' => [
      'max-age' => 0,
    ],

doesn't work with blocks but, like you discovered, it doesn't seem to.

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.