Drupal - Passing current node ID to the block template
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.
Blocks are cached. However blocks are also context-aware in Drupal 8. Per the documentation page regarding Cache Contexts:
Cache contexts provide a declarative way to create context-dependent variations of something that needs to be cached. By making it declarative, code that creates caches becomes easier to read, and the same logic doesn't need to be repeated in every place where the same context variations are necessary.
The Cache API documentation page is a good read for everyone.
A Block plugin should implement getCacheContexts. I think that in this case it should either be "route.name" or "url.path". You may need to delve into this a bit more for your particular use case.
public function getCacheContexts() {
return array('route.name');
}