Passing current node ID to the block template I have a module with a custom block MyCustomBlock.php that get the nid of the current page and pass the value to the block template:

$node = \Drupal::routeMatch()-&gt;getParameter('node');
$nid = $node-&gt;nid-&gt;value;
return array(
  'currentnid' =&gt; $nid,
);


Inside the template I print the passed value {{ currentnid }}, but it only works cleaning the cache! For example, if I load the page with nid 5 it prints 5, but if I move to page with nid 3 it prints 5. Cleaning the cache and reloading page with nid 3 I get the value 3 printed. I think it is a problem with the template caching system in D8, do you have any idea about this?
The proper way to do this would be use contexts. Plugin contexts, not cache contexts.

Similar to NodeType condition plugin, put something like this in your plugin annotation:

* context_definitions = {
*  "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }


And then get the node using $this->getContextValue('node').

This has two advantages:


Your block doesn't rely on global state directly. It could for example be used also in page manager, with a different node.
Drupal automatically understands that your block varies by whatever node is passed in. If using the current node, it will vary by route, if it would e.g. be a node from a static page manager context, it wouldn't. It will also include cache tags, in case the node is changed in a way that would affect your output.