1

I have a site that uses hook_preprocess_block to add a node content type/bundle variable for a block twig template. The template then has logic to display different HTML depending on the node type.

The problem is that caching is breaking this. Whichever variation is cached first is always shown. I think I want to set the cache context for this but not seeing a "node content type" context.

I see some caching related code in the function (I inherited this project) but not sure what it's doing.

function THEME_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, $variables['content']['#block_content']);
  }

  $block_type = $variables['elements']['#configuration']['label'];
  if ($block_type == 'Footer Content Block') {
    $node = \Drupal::routeMatch()->getParameter('node');
    $variables['node_type'] = $node->bundle();
  }
}

1 Answer 1

1

The caching related code already present is for bubbling up the cache dependencies of the block content entity, as a precaution in case the template doesn't render the entire {{ content }} variable.

The second code block is using the current route and then it has to add this as cache dependency:

$variables['#cache']['contexts'][] = 'route';
2
  • Thanks that works. That's a lot of extra unnecessary caching entries though for each route. Too bad content type/bundle isn't a context.
    – codesmith
    Commented Sep 10 at 22:45
  • You can add a module with this cache context. But if you only have a few variations, you could place the same content block multiple times, with different labels (footer 1, footer 2, ...) to use in your code and different visibility settings for the content type (a core plugin).
    – 4uk4
    Commented Sep 11 at 6:54

Your Answer

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

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