-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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