I have this very basic block which just shows the current node’s ID.
<?php /** * @file * Contains DrupalmymodulePluginBlockExampleEmptyBlock. */ namespace DrupalmymodulePluginBlock; use DrupalCoreBlockBlockBase; use DrupalCoreCacheCache; /** * @Block( * id = "example_empty", * admin_label = @Translation("Example: empty block") * ) */ class ExampleEmptyBlock extends BlockBase { /** * {@inheritdoc} */ public function build() { $node = Drupal::routeMatch()->getParameter('node'); $build = array(); if ($node) { $config = Drupal::config('system.site'); $build = array( '#type' => 'markup', '#markup' => '<p>' . $node->id() . '<p>', '#cache' => array( 'tags' => $this->getCacheTags(), 'contexts' => $this->getCacheContexts(), ), ); } return $build; } /** * {@inheritdoc} */ public function getCacheTags() { $node = Drupal::routeMatch()->getParameter('node'); return Cache::mergeTags(parent::getCacheTags(), ["node:{$node->id()}"]); } /** * {@inheritdoc} */ public function getCacheContexts() { return Cache::mergeContexts(parent::getCacheContexts(), ['user.node_grants:view']); } }
But once cached, the block stays the same, regardless which node I visit. How do I correctly cache the result per node ID?