Skip to main content
Drupal 8 catching

Drupal 8 block caching

The approach to custom block caching is different in Drupal 8 from Drupal 7. In Drupal 8, all renderable arrays are cacheable, even those returned by custom block.

Examples:

  • Some expensive-to-calculate data depends on the active theme: different results for different themes. Then you'd vary by the theme cache context.

  • When creating a render array that shows a personalized message, the render array varies per user. Then you'd vary (the render array) by the user cache context.

  • Generally, when some expensive-to-calculate information varies by some environmental context.
    Then vary by a cache context.

The new and much-improved cache API in Drupal 8 provides a sophisticated approach to caching all renderable items whether pages, entities or, in our case blocks too. Drupal 8 allows developers to manage cache behavior for blocks directly in the render array returned by the block object's "build()" method.

In Drupal 7, caching a block by role looks this:

function mymodule_block_info() {
  $blocks = array();
  $blocks['mymodule_example_block'] = array(
    'info' => t('Block title'),
    // Block caching options (per role, per user, etc.)
    // DRUPAL_NO_CACHE is the default.
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

In Drupal 8, cache settings are manipulated directly in renderable arrays returned by (among other things) a block's build() method:

class MyCustomBlock extends BlockBase {
  public function build() {
    return array(
     '#markup' => $markup,
       '#cache' => array(
         'contexts' => array(
         'url.path',
        ),
      ),
    );
  }
}

Available parameters for manipulating cache settings include 'keys', 'contexts', 'tags', 'max-age' and 'bin'.

Drupal 8 core's cache contexts:

   Drupal 8 core ships with the following hierarchy of cache contexts:

cookies
  :name
headers
  :name
ip
languages
  :type
request_format
route
  .book_navigation
  .menu_active_trails
    :menu_name
  .name
session
  .exists
theme
timezone
url
  .host
  .query_args
    :key
    .pagers
      :pager_id
  .path
  .site
user
  .is_super_user
  .node_grants
    :operation
  .permissions
  .roles
    :role


Detailed documentation about cache management in Drupal 8 is available on Drupal.org.