Cache Context and Tags

2 minutes

In Drupal 10, the caching system is crucial for improving the performance of your website. Two key concepts in this system are cache contexts and cache tags. We will explore what they are and how they are used. 

Cache Context

Cache contexts in Drupal determine the variations in content stored in cache. These are useful when you want the content to vary based on certain factors, such as the user viewing the page or the language selected.

Cache Tags

Cache tags are used to invalidate cached content when relevant changes occur. This ensures that users always see the most up-to-date information. 

Use Cases

  • Dependent content: Use the cache context 'user' for content that changes based on the user viewing it.
  • Multilingual content: Use the context 'languages' to ensure that content is stored in cache separately for each language.
  • Content lists: Use tags like 'node_list' to invalidate lists of content when nodes are added or removed.
  • Customized blocks: Apply specific tags to blocks to invalidate them when their content is updated.

Let's combine these two concepts in a block to better understand them. The following code is an example of a block that can be displayed on all content, greeting the user and telling them what content they are viewing, although it's unlikely to be very useful, it can serve as an example:

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;

/**
 * Provides a custom block with cache contexts and tags.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My Custom Block"),
 * )
 */
class MyCustomBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    $user = \Drupal::currentUser();

    $node_title = $node ? $node->getTitle() : $this->t('No node');

    $build = [
      '#markup' => $this->t('Hello, @user! You are viewing: @title', [
        '@user' => $user->getDisplayName(),
        '@title' => $node_title,
      ]),
      '#cache' => [
        'contexts' => [
          'user',
          'route.node',
        ],
        'tags' => $node ? ['node:' . $node->id()] : [],
        'max-age' => Cache::PERMANENT,
      ],
    ];

    return $build;
  }

}
 

What's happening and how caching is being configured:

  • build() method: This method builds the content of the block.
  • Obtaining data:
    • Retrieves the current node from the route.
    • Retrieves the current user.
    • Block content: Creates a message that includes the user's name and the node's title.
  • Caching: Configures caching settings:
    • Contexts: 'user' and 'route.node' to vary content based on user and node.
    • Tags: Uses the node's ID tag to invalidate the cache when the node is updated, useful if the node's title changes.
    • Max-age: Set to permanent.
  • Rendering: The method returns a renderable array with the markup and caching configuration. 

Conclusion

Understand and use cache contexts and tags correctly in Drupal 10 to create faster and more efficient websites, ensuring that the correct content is displayed to the right users at the right time.

Jidrone Drupal Developer
J. Ivan Duarte
Drupal Senior Developer

Share