Block Caching

Articles & Reference

Examples

Disable caching

Render array

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

UncacheableDependencyTrait

use Drupal\Core\Cache\UncacheableDependencyTrait;

/**
 * Example Block.
 *
 * @Block(
 *   id = "example_block",
 *   admin_label = @Translation("Example"),
 * )
 */
class ExampleBlock extends BlockBase {

  use UncacheableDependencyTrait;

Cache by route

  • A version of the block is cached for each path, including paths with parameters
    e.g.: node/{id}, my-entity/{id}
  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
  }