Skip to content

Instantly share code, notes, and snippets.

@drubb
Last active December 7, 2022 22:38
Show Gist options
  • Save drubb/28b1cb5389fd33c3746b52ad57c0a0f6 to your computer and use it in GitHub Desktop.
Save drubb/28b1cb5389fd33c3746b52ad57c0a0f6 to your computer and use it in GitHub Desktop.
Drupal 9 block using node context. Works for node pages, node revision pages and node previews.
<?php
namespace Drupal\title_block\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a block rendering the title of the current node.
*
* @Block(
* id = "title_block_new",
* admin_label = @Translation("Current node title (new)"),
* category = @Translation("Title Block"),
* context_definitions = {
* "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }
* )
*/
class NewBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build(): array {
$node = $this->getContextValue('node');
if (!$node) {
return [];
}
$build['content'] = [
'#markup' => $node->label(),
];
return $build;
}
/**
* {@inheritdoc}
*/
public function getCacheMaxAge() {
// Disable block caching on preview pages to handle recurring previews,
// which would be cached otherwise (same url used for one edit session).
$preview = \Drupal::service('current_route_match')
->getRawParameter('node_preview');
if ($preview) {
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment