Skip to content

Instantly share code, notes, and snippets.

@jcicero518
Forked from drubb/NewBlock.php
Created December 7, 2022 22:38
Show Gist options
  • Save jcicero518/4cb9c51a5b7d89770c12dac31f4590e5 to your computer and use it in GitHub Desktop.
Save jcicero518/4cb9c51a5b7d89770c12dac31f4590e5 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