I have a custom block

'#attached' => [
  'drupalSettings' => [
    'myblock' => $settings

When I do not turn off cache, the settings are properly written into JS variables and I can fetch them in frontend. But I need to work with images on pages and when this block is cached, it is not displayed per page, but there is the first data loaded (so page 1 has the same data as page 2, although I need different data and I fetch different data).

This can be solved by turning off the cache

public function getCacheMaxAge() {
  return 0;

But then the variable in JS is not set and I cannot fetch it in frontend. Why?

  • Solved by cache context public function getCacheContexts() { $cache_contexts = parent::getCacheContexts(); $cache_contexts[] = 'url.path'; return $cache_contexts; } But the question remains.
    – Ari
    May 25 at 10:04
  • The correct way to add a cache max age to #attached would be #cache, not a plugin method. Does it make a difference if you have the module BigPipe enabled or not?
    – 4uk4
    May 25 at 11:41
  • @4uk4 I have a Block plugin that does stuff I need. Why shouldn't I use a plugin method, if I want to change cache for the block purely? What is the purpose of the method then? And no, BigPipe uninstall does not have any effect. I also tried this '#attachements' => [ '#cache' => ['#tags' => 0]] ]; in my build() method, if I understand your message correctly. But the same problem occurs - no data in drupalSettings whatsoever.
    – Ari
    May 25 at 12:42
  • 1
    #attachments and #cache have to be on the same level. A block with cache max age 0 is placeholdered in the page by default and when this placeholder is replaced the included attachments have to be added to the already built page. With BigPipe enabled this takes place in the client via ajax.js. The plugin methods by the way are common to all cacheable plugins which often don't build render arrays. In case they do, it should not be a replacement for building correct render arrays.
    – 4uk4
    May 25 at 13:01


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.

Browse other questions tagged or ask your own question.