I have this very basic block which just shows the current node's ID.
<?php /** * @file * Contains \Drupal\mymodule\Plugin\Block\ExampleEmptyBlock. */ namespace Drupal\mymodule\Plugin\Block; use Drupal\Core\Block\BlockBase; use Drupal\Core\Cache\Cache; /** * @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?
getCacheTags()from BlockBase, you just need add a tag that represent your node (node:{nid}). Sorry I'm in a hurry now, I can explain better later,